Encode / decode URLs

后端 未结 8 1522
攒了一身酷
攒了一身酷 2020-11-28 03:46

What\'s the recommended way of encoding and decoding entire URLs in Go? I am aware of the methods url.QueryEscape and url.QueryUnescape, but they d

8条回答
  •  无人及你
    2020-11-28 04:29

    You can do all the URL encoding you want with the net/url module. It doesn't break out the individual encoding functions for the parts of the URL, you have to let it construct the whole URL. Having had a squint at the source code I think it does a very good and standards compliant job.

    Here is an example (playground link)

    package main
    
    import (
        "fmt"
        "net/url"
    )
    
    func main() {
    
        Url, err := url.Parse("http://www.example.com")
        if err != nil {
            panic("boom")
        }
    
        Url.Path += "/some/path/or/other_with_funny_characters?_or_not/"
        parameters := url.Values{}
        parameters.Add("hello", "42")
        parameters.Add("hello", "54")
        parameters.Add("vegetable", "potato")
        Url.RawQuery = parameters.Encode()
    
        fmt.Printf("Encoded URL is %q\n", Url.String())
    }
    

    Which prints

    Encoded URL is "http://www.example.com/some/path/or/other_with_funny_characters%3F_or_not/?vegetable=potato&hello=42&hello=54"
    

提交回复
热议问题