Skip to content

Instantly share code, notes, and snippets.

@sonyarianto
Created December 5, 2018 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonyarianto/47b2e2fd4c3103bf699c3c3b1b86040f to your computer and use it in GitHub Desktop.
Save sonyarianto/47b2e2fd4c3103bf699c3c3b1b86040f to your computer and use it in GitHub Desktop.
Web routing with gorilla/mux
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
func Home(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "This is the home page")
}
func Article(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fmt.Fprintf(w, "Article id is %s", vars["id"])
}
func Number(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fmt.Fprintf(w, "This is number %s", vars["id"])
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", Home)
r.HandleFunc("/article/{id}", Article) // {id} can be anything
r.HandleFunc("/number/{id:[0-9]+}", Number) // only match numeric pattern
log.Fatal(http.ListenAndServe(":3000", r))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment