Skip to content

Instantly share code, notes, and snippets.

@dennypenta
Created June 5, 2024 18:23
Show Gist options
  • Save dennypenta/0d465373ce4efed9c593e28d7c33dd5a to your computer and use it in GitHub Desktop.
Save dennypenta/0d465373ce4efed9c593e28d7c33dd5a to your computer and use it in GitHub Desktop.
type Error struct {
Code string `json:"code"`
Message string `json:"message"`
Meta map[string]string `json:"meta"`
}
type Handler[I, O comparable] func(ctx context.Context, i I) (O, *handlers.Error)
func NewHandler[I, O comparable](call Handler[I, O]) http.HandlerFunc {
hasReqBody := unsafe.Sizeof(i) != 0
hasResBody := unsafe.Sizeof(res) != 0
return func(w http.ResponseWriter, r *http.Request) {
var i I
if hasReqBody {
if err := json.NewDecoder(r.Body).Decode(&i); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(handlers.Error{
Code: "FAILED_DECODING",
Message: err.Error(),
})
return
}
}
res, callErr := call(r.Context(), i)
if callErr != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(callErr)
return
}
if hasResBody {
if err := json.NewEncoder(w).Encode(res); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(handlers.Error{
Code: "FAILED_ENCODING",
Message: err.Error(),
})
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment