...

Source file src/github.com/go-chi/chi/_examples/router-walk/main.go

Documentation: github.com/go-chi/chi/_examples/router-walk

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/go-chi/chi"
     9  )
    10  
    11  func main() {
    12  	r := chi.NewRouter()
    13  	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
    14  		w.Write([]byte("root."))
    15  	})
    16  
    17  	r.Route("/road", func(r chi.Router) {
    18  		r.Get("/left", func(w http.ResponseWriter, r *http.Request) {
    19  			w.Write([]byte("left road"))
    20  		})
    21  		r.Post("/right", func(w http.ResponseWriter, r *http.Request) {
    22  			w.Write([]byte("right road"))
    23  		})
    24  	})
    25  
    26  	r.Put("/ping", Ping)
    27  
    28  	walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
    29  		route = strings.Replace(route, "/*/", "/", -1)
    30  		fmt.Printf("%s %s\n", method, route)
    31  		return nil
    32  	}
    33  
    34  	if err := chi.Walk(r, walkFunc); err != nil {
    35  		fmt.Printf("Logging err: %s\n", err.Error())
    36  	}
    37  }
    38  
    39  // Ping returns pong
    40  func Ping(w http.ResponseWriter, r *http.Request) {
    41  	w.Write([]byte("pong"))
    42  }
    43  

View as plain text