Created
December 5, 2018 09:41
-
-
Save sonyarianto/47b2e2fd4c3103bf699c3c3b1b86040f to your computer and use it in GitHub Desktop.
Web routing with gorilla/mux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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