I am trying to add a query parameter to a HTTP GET request but somehow methods pointed out on SO (e.g. here) don't work.
I have the following piece of code:
package main import ( "fmt" "log" "net/http" ) func main() { req, err := http.NewRequest("GET", "/callback", nil) req.URL.Query().Add("code", "0xdead 0xbeef") req.URL.Query().Set("code", "0xdead 0xbeef") // this doesn't help //req.URL.RawQuery = req.URL.Query().Encode() if err != nil { log.Fatal(err) } fmt.Printf("URL %+v\n", req.URL) fmt.Printf("RawQuery %+v\n", req.URL.RawQuery) fmt.Printf("Query %+v\n", req.URL.Query()) }
which prints:
URL /callback RawQuery Query map[]
Any suggestions on how to achieve this?
Playground example: https://play.golang.org/p/SYN4yNbCmo
Unless there's something sensitive in the request parameters, it is perfectly fine to send them as part of URL.
To do http get request with parameters in Angular, we can make use of params options argument in HttpClient. get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.
When the GET request method is used, if a client uses the HTTP protocol on a web server to request a certain resource, the client sends the server certain GET parameters through the requested URL. These parameters are pairs of names and their corresponding values, so-called name-value pairs.
Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".
Check the docs for req.URL.Query()
:
Query parses RawQuery and returns the corresponding values.
Since it "parses RawQuery and returns" the values what you get is just a copy of the URL query values, not a "live reference", so modifying that copy does nothing to the original query. In order to modify the original query you must assign to the original RawQuery
.
q := req.URL.Query() // Get a copy of the query values. q.Add("code", "0xdead 0xbeef") // Add a new value to the set. req.URL.RawQuery = q.Encode() // Encode and assign back to the original query. // URL /callback?code=0xdead+0xbeef // RawQuery code=0xdead+0xbeef // Query map[code:[0xdead 0xbeef]]
Note that your original attempt to do so didn't work because it simply parses the query values, encodes them, and assigns them right back to the URL:
req.URL.RawQuery = req.URL.Query().Encode() // This is basically a noop!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With