...

Source file src/github.com/go-chi/chi/_examples/custom-handler/main.go

Documentation: github.com/go-chi/chi/_examples/custom-handler

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"net/http"
     6  
     7  	"github.com/go-chi/chi"
     8  )
     9  
    10  type Handler func(w http.ResponseWriter, r *http.Request) error
    11  
    12  func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    13  	if err := h(w, r); err != nil {
    14  		// handle returned error here.
    15  		w.WriteHeader(503)
    16  		w.Write([]byte("bad"))
    17  	}
    18  }
    19  
    20  func main() {
    21  	r := chi.NewRouter()
    22  	r.Method("GET", "/", Handler(customHandler))
    23  	http.ListenAndServe(":3333", r)
    24  }
    25  
    26  func customHandler(w http.ResponseWriter, r *http.Request) error {
    27  	q := r.URL.Query().Get("err")
    28  
    29  	if q != "" {
    30  		return errors.New(q)
    31  	}
    32  
    33  	w.Write([]byte("foo"))
    34  	return nil
    35  }
    36  

View as plain text