Skip to content

Instantly share code, notes, and snippets.

@davidlares
Last active July 14, 2021 00:47
Show Gist options
  • Save davidlares/1583176139ae12cd1f3ecaadd26dd8b1 to your computer and use it in GitHub Desktop.
Save davidlares/1583176139ae12cd1f3ecaadd26dd8b1 to your computer and use it in GitHub Desktop.
Golang's Mux HTTP GET request with params
package main
import (
"github.com/gorilla/mux"
"net/http"
"fmt"
)
func main() {
// new mux router
r := mux.NewRouter()
//Methods
r.HandleFunc("/test/{name}/{page}", myHandlerFunc)
r.HandleFunc("/", postHandler).Methods("POST")
r.HandleFunc("/", getHandler).Methods("GET")
// server instance
http.ListenAndServe(":8080", r)
}
// GET request with params
func myHandlerFunc(w http.ResponseWriter, r *http.Request) {
// getting the params (mux way)
vars := mux.Vars(r)
// getting each one
name := vars["name"]
page := vars["page"]
// printing
fmt.Fprintln(w, "name: ", name)
fmt.Fprintln(w, "page: ", page)
// At this point you need to validate
}
// GET request handler
func getHandler(w http.ResponseWriter, r *http.Request) {
// same logic
}
// POST request handler
func postHandler(w http.ResponseWriter, r *http.Request) {
// some logic
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment