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
+18.9k Golang : Check whether a network interface is up on your machine
+14.7k Golang : Submit web forms without browser by http.PostForm example
+10k Golang : Print how to use flag for your application example
+16.3k Golang : Execute terminal command to remote machine example
+13.2k Golang : Verify token from Google Authenticator App
+8.3k Golang : How to check if input string is a word?
+16.2k CodeIgniter/PHP : Create directory if does not exist example
+3.5k Java : Get FX sentiment from website example
+9.7k Golang : Get current, epoch time and display by year, month and day
+20k Golang : Count number of digits from given integer value
+18.2k Golang : Read binary file into memory
+5.3k Golang : If else example and common mistake