map to URL query string

15,007 views
Skip to first unread message

enigma

unread,
Aug 6, 2010, 11:19:24 AM8/6/10
to golang-nuts
Hi,
What would be the idiomatic way to create a url query string
(mapToQueryString) from a
map.
m map[stiring] string {
"a": "xZZ",
"b": "sZZ"
}

var url http.URL
url.RawQuery = mapToQueryString(m)
Thanks

Michael Hoisie

unread,
Aug 6, 2010, 1:39:25 PM8/6/10
to golang-nuts
There isn't a library method to do this, but I've used this code
before:

func Urlencode(data map[string]string) string {
var buf bytes.Buffer
for k, v := range data {
buf.WriteString(http.URLEscape(k))
buf.WriteByte('=')
buf.WriteString(http.URLEscape(v))
buf.WriteByte('&')
}
s := buf.String()
return s[0 : len(s)-1]

Cody Goodman

unread,
Jan 13, 2013, 1:23:10 AM1/13/13
to golan...@googlegroups.com
This came in a search recently for me, and there is since what I believe a more idiomatic way of doing this:

For those who want an example to play with: http://play.golang.org/p/kcBAs--SZy

For those who can't be bothered to click through to another link and would otherwise just copy paste the code above:

package main

import (
"fmt"
"net/url"
)

func main() {
// way 1
params := url.Values{}
params.Add("query", "keyword")
finalUrl := baseUrl + params.Encode()
fmt.Println(finalUrl)

michae...@gmail.com

unread,
Feb 24, 2014, 4:22:54 PM2/24/14
to golan...@googlegroups.com
Yet another take on the same problem: just let the library do all the work.

http://play.golang.org/p/sxmhsLQOYw

baseUrl, err := url.Parse("http://google.com/search")
if err != nil {
log.Fatal(err)
}

params := url.Values{}
params.Add("pass%word", "key%20word")

baseUrl.RawQuery = params.Encode()
fmt.Println(baseUrl)

Michael

pun...@gmail.com

unread,
Jan 1, 2015, 5:47:48 PM1/1/15
to golan...@googlegroups.com, michae...@gmail.com
This is gold, thanks. I would have never seen that the URL struct had a field for the query values :D
Reply all
Reply to author
Forward
0 new messages