Skip to content

Instantly share code, notes, and snippets.

@narenaryan
Created March 22, 2017 03:26
Show Gist options
  • Select an option

  • Save narenaryan/4359331ee1ed3ca359332d0294a49329 to your computer and use it in GitHub Desktop.

Select an option

Save narenaryan/4359331ee1ed3ca359332d0294a49329 to your computer and use it in GitHub Desktop.
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