httpin
httpin copied to clipboard
bump version to 1.0.0
I'm planing to publish the first stable release of this program. If any of you were using this library in your production environment, please feel free to leave a comment below. A breif description of your application scenarios will bring great helps ❤️
Hi, i'm looking at using your lib like this
package main
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/ggicci/httpin"
)
type Request[T any] struct {
*http.Request
Data *T
}
type Response[T any] struct {
StatusCode int
Data *T
}
// Handler defines generic HTTP handler function.
type Handler[I, O any] func(*Request[I]) (*Response[O], error)
// Wrap wraps generic handler into Go idiomatic HTTP handler function.
// Request is parsed using [httpin.Decode].
// Response from generic handler is automatically JSON encoded and passed to idiomatic HTTP handler.
func Wrap[I, O any](handler Handler[I, O]) func(http.ResponseWriter, *http.Request) {
return func(res http.ResponseWriter, req *http.Request) {
var reqData I
err := httpin.Decode(req, &reqData)
if err != nil {
return
}
r, err := handler(&Request[I]{Request: req, Data: &reqData})
if err != nil {
slog.Error("handler", "error", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
render(res, r)
}
}
func render[O any](res http.ResponseWriter, response *Response[O]) {
res.Header().Set("Content-Type", "application/json")
resData, err := json.Marshal(response.Data)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
if response.StatusCode == 0 {
response.StatusCode = http.StatusOK
}
res.WriteHeader(response.StatusCode)
_, _ = res.Write(resData)
}
Hi @emilien-puget , sorry I missed the message. But I still want to say thank you for your sharing your use case!