0xBF
0xBF

0xBF

Go Cheatsheet - url parse / encode

0xBF's photo
0xBF

Published on Apr 22, 2021

1 min read

URL

URL Parse

import (
    "fmt"
    "net/url"
)

func main() {
    loc := "https://youdomain.com:8080/path?kw=search&lang=en"
    parsed, _ := url.Parse(loc)
    serialized, _ := json.MarshalIndent(parsed, "", "  ")
    fmt.Println(string(serialized))
    fmt.Println("Scheme:", parsed.Scheme)
    fmt.Println("Host:", parsed.Host)
    fmt.Println("Hostname:", parsed.Hostname())
    fmt.Println("Port:", parsed.Port())
    fmt.Println("Query map:", parsed.Query())
}

Result:

{
  "Scheme": "https",
  "Opaque": "",
  "User": null,
  "Host": "youdomain.com:8080",
  "Path": "/path",
  "RawPath": "",
  "ForceQuery": false,
  "RawQuery": "kw=search\u0026lang=en",
  "Fragment": "",
  "RawFragment": ""
}
Scheme: https
Host: youdomain.com:8080
Hostname: youdomain.com
Port: 8080
Query map: map[kw:[search] lang:[en]]

URL Escape

import (
    "fmt"
    "net/url"
)

func main() {
    q := "hello world"
    escaped := url.QueryEscape(q)
    fmt.Println("Escaped:", escaped)
    unescaped, _ := url.QueryUnescape(escaped)
    fmt.Println("Unescaped:", unescaped)
}

Result:

Escaped: hello+world
Unescaped: hello world

Encode Map to Query String

func mapToQueryString(m map[string]string) string {
    val := url.Values{}
    for k, v := range m {
        val.Add(k, string(v))
    }
    return val.Encode()
}

func main() {
    params := map[string]string{
        "kw":   "hello world",
        "lang": "en",
    }
    fmt.Println("Param string:", mapToQueryString(params))
}

Result:

Param string: kw=hello+world&lang=en

Parse Query String to Map/Values

func main() {
    qs := "kw=hello+world&lang=en"
    val, _ := url.ParseQuery(qs)
    fmt.Println(val.Get("kw"))
    fmt.Println(val.Get("lang"))
}

Result:

hello world
en
 
Share this