Last active
July 14, 2021 00:47
-
-
Save davidlares/1583176139ae12cd1f3ecaadd26dd8b1 to your computer and use it in GitHub Desktop.
Golang's Mux HTTP GET request with params
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" | |
"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