Go doing a GET request and building the Querystring

后端 未结 3 580
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 11:53

I am pretty new to Go and don\'t quite understand everything as yet. In many of the modern languages Node.js, Angular, jQuery, PHP you can do a GET request with additional q

3条回答
  •  鱼传尺愫
    2020-12-07 12:41

    Using NewRequest just to create an URL is an overkill. Use the net/url package:

    package main
    
    import (
        "fmt"
        "net/url"
    )
    
    func main() {
        base, err := url.Parse("http://www.example.com")
        if err != nil {
            return
        }
    
        // Path params
        base.Path += "this will get automatically encoded"
    
        // Query params
        params := url.Values{}
        params.Add("q", "this will get encoded as well")
        base.RawQuery = params.Encode() 
    
        fmt.Printf("Encoded URL is %q\n", base.String())
    }
    

    Playground: https://play.golang.org/p/YCTvdluws-r

提交回复
热议问题