Created
March 22, 2017 03:26
-
-
Save narenaryan/4359331ee1ed3ca359332d0294a49329 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
| "github.com/gorilla/mux" | |
| "log" | |
| "net/http" | |
| "time" | |
| "fmt" | |
| ) | |
| func ArticleHandler(w http.ResponseWriter, r *http.Request){ | |
| vars := mux.Vars(r) | |
| w.WriteHeader(http.StatusOK) | |
| fmt.Fprintf(w, "Category is: %v\n", vars["category"]) | |
| fmt.Fprintf(w, "ID is: %v\n", vars["id"]) | |
| } | |
| func QueryHandler(w http.ResponseWriter, r *http.Request){ | |
| queryParams := r.URL.Query() | |
| w.WriteHeader(http.StatusOK) | |
| fmt.Fprintf(w, "Got parameter %s!", queryParams["id"]) | |
| fmt.Fprintf(w, "Got parameter %s!", queryParams["category"]) | |
| } | |
| func main(){ | |
| // Create a new router | |
| r := mux.NewRouter() | |
| // Attach an elegant path with handler | |
| r.HandleFunc("/articles", QueryHandler) | |
| r.Queries("id", "category") | |
| srv := &http.Server{ | |
| Handler: r, | |
| Addr: "127.0.0.1:8080", | |
| // Good practice: enforce timeouts for servers you create! | |
| WriteTimeout: 15 * time.Second, | |
| ReadTimeout: 15 * time.Second, | |
| } | |
| log.Fatal(srv.ListenAndServe()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment