Go net/http request

前端 未结 1 1053
死守一世寂寞
死守一世寂寞 2021-02-11 11:27

Can somebody help to convert my ruby code to Go. Kindly refer to my ruby code below.

 query=       \"test\"
 request =        Net::HTTP::Post.new(url)
 request.         


        
相关标签:
1条回答
  • 2021-02-11 12:09

    You seem to want to POST a query, which would be similar to this answer:

    import (
        "bytes"
        "fmt"
        "io/ioutil"
        "net/http"
    )
    
    
    func main() {
        url := "http://xxx/yyy"
        fmt.Println("URL:>", url)
    
        var query = []byte(`your query`)
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(query))
        req.Header.Set("X-Custom-Header", "myvalue")
        req.Header.Set("Content-Type", "text/plain")
    
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()
    
        fmt.Println("response Status:", resp.Status)
        fmt.Println("response Headers:", resp.Header)
        body, _ := ioutil.ReadAll(resp.Body)
        fmt.Println("response Body:", string(body))
    }
    

    Replace "text/plain" with "application/json" if your query is a JSON one.

    0 讨论(0)
提交回复
热议问题