Skip to content

Instantly share code, notes, and snippets.

@icholy
Last active April 10, 2023 19:34
Show Gist options
  • Save icholy/96adfe04a7cc86f616b2539fd4fde4eb to your computer and use it in GitHub Desktop.
Save icholy/96adfe04a7cc86f616b2539fd4fde4eb to your computer and use it in GitHub Desktop.
package httpx
import (
"net/http"
)
func WithStatus(code int, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(code)
handler.ServeHTTP(w, r)
})
}
func AsJSON(v interface{}) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(v)
})
}
type StatusError struct {
Status int
Message string
}
func (e StatusError) Error() string {
return e.Message
}
func (e StatusError) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, e.Message, e.Status)
}
func Errorf(code int, format string, a ...interface{}) http.Handler {
return StatusError{
Status: code,
Message: fmt.Sprintf(format, a...),
}
}
func Error(code int, a ...interface{}) http.Handler {
return StatusError{
Status: code,
Message: fmt.Sprint(a...),
}
}
type HandlerFunc func(http.ResponseWriter, *http.Request) http.Handler
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if handler := f(w, r); handler != nil {
handler(w, r)
}
}
func HandleFunc(pattern string, handler HandlerFunc) {
http.Handle(patten, handler)
}
func main() {
httpx.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) http.Handler {
return httpx.Error(500, "what")
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment