The recommended way to use httpin in a web server is via NewInput(). This creates an http.Handler middleware that:
- Decodes the incoming request into the specified struct type.
- If decoding fails, it invokes the configured error handler and terminates the request.
- If successful, it injects the decoded struct into the request's context using the
httpin.Input key.
To retrieve the decoded struct in your handler, use r.Context().Value(httpin.Input).(*YourStruct).
type ListUsersRequest struct {
Page int `in:"query=page,page_index,index"`
PerPage int `in:"query=per_page,page_size"`
}
func ListUsersHandler(rw http.ResponseWriter, r *http.Request) {
input := r.Context().Value(httpin.Input).(*ListUsersRequest)
// ... use input
}
func init() {
http.Handle("/users", httpin.NewInput(&ListUsersRequest{})(nextHandler))
}
type ListUsersRequest struct {
Page int `in:"query=page,page_index,index"`
PerPage int `in:"query=per_page,page_size"`
}
func ListUsersHandler(rw http.ResponseWriter, r *http.Request) {
input := r.Context().Value(httpin.Input).(*ListUsersRequest)
// ...
}
func init() {
http.Handle("/users", httpin.NewInput(&ListUsersRequest{}).ThenFunc(ListUsersHandler))
}