Go doing a GET request and building the Querystring

后端 未结 3 577
伪装坚强ぢ
伪装坚强ぢ 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:36

    As a commenter mentioned you can get Values from net/url which has an Encode method. You could do something like this (req.URL.Query() returns the existing url.Values)

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
        "os"
    )
    
    func main() {
        req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
        if err != nil {
            log.Print(err)
            os.Exit(1)
        }
    
        q := req.URL.Query()
        q.Add("api_key", "key_from_environment_or_flag")
        q.Add("another_thing", "foo & bar")
        req.URL.RawQuery = q.Encode()
    
        fmt.Println(req.URL.String())
        // Output:
        // http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
    }
    

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

提交回复
热议问题