Parsing URL Query Parameters
A minimal example of parsing query parameters on get requests
This is a small example of how to parse url query parameters in Go. I was learning this in service of another project, in which case I wanted the parameters in the map[string]string
format, but this doesn’t always need to be the case.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
)
func DemoGet(w http.ResponseWriter, r *http.Request) {
:= r.URL.Query()
urlParams
//in a use case for another project, i want the urlParams to be encoded as a map[string]string
//but this won't always be the use case
:= make(map[string]string, len(urlParams))
m
for i, v := range urlParams {
//in prod, we probably don't want to error out
//but yolo for now
if len(v) > 1 {
.Fatal("query parameters should all be length 1")
log}
:= strings.Join(v, "")
s [i] = s
m}
.Header().Set("Content-Type", "application/json")
w
.NewEncoder(w).Encode(m)
json}
func main() {
:= http.NewServeMux()
r
.HandleFunc("/demoget", DemoGet)
r
:= &http.Server{
s : ":8080",
Addr: r,
Handler}
.Println("Running demo program")
fmt
.ListenAndServe()
s}