mirror of
https://github.com/ggicci/httpin.git
synced 2024-11-28 08:49:05 +02:00
🍡 HTTP Input for Go - Decode an HTTP request into a custom struct 📢 the encoding feature will come soon, see branch feat/encoder
https://ggicci.github.io/httpin/
.github/workflows | ||
internal | ||
patch | ||
.gitignore | ||
body_test.go | ||
body.go | ||
chain.go | ||
debug.go | ||
decoders.go | ||
directives_test.go | ||
directives.go | ||
errors.go | ||
form.go | ||
go.mod | ||
go.sum | ||
httpin_test.go | ||
httpin.go | ||
LICENSE | ||
Makefile | ||
README.md | ||
required.go | ||
resolver_test.go | ||
resolver.go |
httpin
HTTP Input for Go
Quick View
BEFORE (use functions provided by net/http lib) | AFTER (use httpin to extract input parameters from HTTP request) |
---|---|
|
|
Features
- Decode from HTTP query, i.e.
http.Request.Form
- Decode from HTTP headers, e.g.
http.Request.Header
- Builtin decoders for basic types, e.g.
bool
,int
,int64
,float32
,time.Time
, ... full list - Decode one field by inspecting multiple keys one by one in the same source
- Decode one field from multiple sources, e.g. both query and headers
- Customize decoders for user defined types
- Define input struct with embedded struct fields
- Tag one field as required
- Builtin encoders for basic types
- Customize encoders for user defined types
Sample User Defined Input Structs
type Authorization struct {
// Decode from multiple sources, the former with higher priority
Token string `in:"form=access_token,header=x-api-token"`
}
type Pagination struct {
Page int `in:"form=page"`
// Decode from multiple keys in the same source, the former with higher priority
PerPage int `in:"form=per_page,page_size"`
}
type ListUsersInput struct {
Gender string `in:"form=gender"`
AgeRange []int `in:"form=age_range"`
IsMember bool `in:"form=is_member"`
Pagination // Embedded field works
Authorization // Embedded field works
}
Advanced - Use Middleware
First, set up the middleware for your handlers. We recommend using alice to chain your HTTP middleware functions.
func init() {
mux.Handle("/users", alice.New(
httpin.NewInput(ListUsersInput{}),
).ThenFunc(ListUsers)).Methods("GET")
}
Second, fetch your input with only one line of code.
func ListUsers(rw http.ResponseWriter, r *http.Request) {
input := r.Context().Value(httpin.Input).(*UserQuery)
// do sth.
}