You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The various packages under the server package have code duplication: a lot of HTTP handler functions unmarshal their input and then marshal their output in exactly the same way. This could be solved using Go generics, with a generic helper function that deals with the (un)marshaling:
// GenericHandlerFunc is a HTTP handler function that takes typed input and output,// which is JSON-(un)marshaled automatically by WrapGenericHandler.typeGenericHandlerFunc[InType, OutTypeany] func(
input*InType, w http.ResponseWriter, r*http.Request,
) (OutType, *server.Error, error)
// WrapGenericHandler wraps a GenericHandlerFunc into an ordinary http.HandlerFunc.funcWrapGenericHandler[InType, OutTypeany](handlerGenericHandlerFunc[InType, OutType]) http.HandlerFunc {
returnfunc(w http.ResponseWriter, r*http.Request) {
input:=new(InType)
iferr:=server.ParseBody(r, input); err!=nil {
server.WriteError(w, server.ErrorInvalidRequest, err.Error())
return
}
output, servErr, err:=handler(input, w, r)
iferr!=nil {
ifservErr==nil {
servErr=&server.ErrorInternal
}
// Logging of the error should be done in the handler where the details of the error are knownserver.WriteError(w, *servErr, err.Error())
return
}
server.WriteJson(w, output)
}
}
Example usage code:
typeServerstruct{}
typeInputstruct{ xint }
typeOutputstruct{}
// handleSomeEndpoint handles /endpoint. It takes a typed input parameter and may return// a typed output parameter, or an error.func (s*Server) handleSomeEndpoint(input*Input, w http.ResponseWriter, r*http.Request) (*Output, *server.Error, error) {
// do something useful with input.// w and r may be used as well, as with ordinary http.Handler functions// (but probably that will often not be necessary).// Errors can be returned as follows.ifinput.x==0 {
// Perhaps do some logging herereturnnil, &server.ErrorUnexpectedRequest, errors.New("x was 0")
}
return&Output{}, nil, nil
}
func (s*Server) Handler() http.Handler {
r:=chi.NewRouter()
r.Get("/endpoint", WrapGenericHandler(s.handleSomeEndpoint))
returnr
}
The text was updated successfully, but these errors were encountered:
The various packages under the
server
package have code duplication: a lot of HTTP handler functions unmarshal their input and then marshal their output in exactly the same way. This could be solved using Go generics, with a generic helper function that deals with the (un)marshaling:Example usage code:
The text was updated successfully, but these errors were encountered: