Skip to content

Instantly share code, notes, and snippets.

@nantsou
Created March 10, 2019 03:40
Show Gist options
  • Save nantsou/7f30f79f47022f2da761784d9f15ad9e to your computer and use it in GitHub Desktop.
Save nantsou/7f30f79f47022f2da761784d9f15ad9e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func GetExampleHandler(text string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(text))
}
}
func main() {
mainRouter := mux.NewRouter()
mainRouter.HandleFunc("/main", GetExampleHandler("main"))
sub := mainRouter.PathPrefix("/sub").Subrouter()
subRouter := mux.NewRouter().PathPrefix("/sub").Subrouter()
subRouter.HandleFunc("/", GetExampleHandler("sub top"))
for _, item := range []string{"endpoint1", "endpoint2"} {
subRouter.HandleFunc("/" + item, GetExampleHandler(item))
}
// in mux, you need to register subrouter
// with the same path that the handlers in the main router
sub.Handle("/", subRouter)
// if your subrouter has handlers that match
// other sub paths - you also need to do this
sub.Handle("/{_:.*}", subRouter)
http.ListenAndServe(":5050", mainRouter)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment