Getting Started
httpin is a Go package for decoding HTTP requests into Go structs and encoding Go structs into HTTP requests.
We support decoding
- Query parameters, e.g.
?name=john&is_member=true
- Headers, e.g.
Authorization: Bearer xxx
- Form data, e.g.
username=john&password=******
- JSON/XML Body, e.g.
POST {"name":"john"}
- Path variables, e.g.
/users/{username}
- File uploads
- Patch fields, i.e. tell a field from missing to empty
and more of an HTTP request into a struct in Go. And vice versa, we support encoding a struct into an HTTP request.
Install
go get github.com/ggicci/httpin
Thanks 🥰
If you thought this package helpful, please consider giving it a big star ⭐️. Thanks in advance!
Quick View
// Well define your data.
type ListUsersInput struct {
Page int `in:"query=page"`
PerPage int `in:"query=per_page"`
IsMember bool `in:"query=is_member"`
}
func ListUsers(rw http.ResponseWriter, r *http.Request) {
// Retrieve your data in one line of code!
input := r.Context().Value(httpin.Input).(*ListUsersInput)
// Do sth.
}
Run Demo
Take a look at the integrations section in the left sidebar. You may also find useful runnable demos there.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/ggicci/httpin"
"github.com/go-chi/chi/v5"
)
type ListUsersInput struct {
Token string `in:"header=Authorization"`
IsMember bool `in:"query=is_member"`
AgeRange []int `in:"query=age_range[],age_range"`
}
func ListUsers(rw http.ResponseWriter, r *http.Request) {
input := r.Context().Value(httpin.Input).(*ListUsersInput)
fmt.Printf("input: %#v\n", input)
}
func main() {
router := chi.NewRouter()
router.With(
httpin.NewInput(ListUsersInput{}),
).Get("/users", ListUsers)
r, _ := http.NewRequest("GET", "/users?is_member=1&age_range=18&age_range=60", nil)
r.Header.Set("Authorization", "my-secret-here")
rw := httptest.NewRecorder()
router.ServeHTTP(rw, r)
}
Comparison
Items | Before (use net/http package) | After (use ggicci/httpin package) |
---|---|---|
Developer Time | 😫 Expensive (too much parsing stuff code) | 🚀 Faster (define the struct for receiving input data and leave the parsing job to httpin) |
Code Repetition Rate | 😞 High | Lower |
Code Readability | 😟 Poor | Highly readable |
Maintainability | 😡 Poor | 😍 Highly maintainable |