Golang : Get query string value on a POST request
In this tutorial, we will learn how to configure your Golang web application(in HTTP handler) to accept query string input by POST request such as :
http://example.com/query?firstparameter=somevalue&secondparameter=somevalue
Golang's net/url.URL.Query
will parse query string and returns the corresponding values. All you have to do is the invoke the Get()
method to get the values that you are looking for.
For example :
package main
import (
"fmt"
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello"
html = html + " World"
w.Write([]byte(html))
}
func QueryReply(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
fmt.Println("GET parameters string : ", query)
first := query.Get("first")
second := query.Get("second")
w.Write([]byte("First value : " + first + "\n"))
w.Write([]byte("Second value : " + second + "\n"))
// because query is a map, we can use it like a hash table
// map[first:[1] second:[2]]
// query by the key "first" example
firstvalue := query["first"]
fmt.Println(firstvalue)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/query", QueryReply)
http.ListenAndServe(":8080", mux)
}
Pointing your browser to http://localhost:8080/query?first=1&second=2
will produce:
First value : 1
Second value : 2
NOTE : query
or r.URL.Query()
returns a map, you can retrieve the query value by key.
References :
See also : Get form post value in Go
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.1k Golang : Transform lisp or spinal case to Pascal case example
+8.2k Golang : HttpRouter multiplexer routing example
+15.1k Golang : Get HTTP protocol version example
+14.4k Golang : How to check if your program is running in a terminal
+8k Golang : Multiplexer with net/http and map
+11.1k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+7.2k Golang : How to fix html/template : "somefile" is undefined error?
+11.4k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+8.3k Golang : Count leading or ending zeros(any item of interest) example
+8.7k Golang : Random integer with rand.Seed() within a given range
+7.7k Golang : Example of how to detect which type of script a word belongs to
+18.6k Golang : convert int to string