Skip to content

Instantly share code, notes, and snippets.

@maplebed
Created February 6, 2019 00:19
Show Gist options
  • Save maplebed/313c3208a80433cb60d1a07a995b6510 to your computer and use it in GitHub Desktop.
Save maplebed/313c3208a80433cb60d1a07a995b6510 to your computer and use it in GitHub Desktop.
Play with this by sending requests for /customer, /customer/, and /customer/foo with curl:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func customersGetHandleFunc(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("handling customers\n")))
}
func customerGetByIDHandleFunc(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.Write([]byte(fmt.Sprintf("handling ID %s\n", vars["id"])))
}
func main() {
rtr := mux.NewRouter()
rtrCust := rtr.PathPrefix("/customer").Subrouter()
rtrCust.Path("").
Methods(http.MethodGet).
HandlerFunc(customersGetHandleFunc)
rtrCust.Path("/").
Methods(http.MethodGet).
HandlerFunc(customersGetHandleFunc)
rtrCust.
Path("/{id}").
Methods(http.MethodGet).
HandlerFunc(customerGetByIDHandleFunc)
http.ListenAndServe("localhost:8080", rtr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment