-14

有人可以帮助将我的 ruby​​ 代码转换为 Go。请参考下面我的 ruby​​ 代码。

 query=       "test"
 request =        Net::HTTP::Post.new(url)
 request.body =     query
 response =   Net::HTTP.new(host, post).start{|http http.request(request)}   

去。

4

1 回答 1

22

您似乎想发布一个查询,该查询类似于此答案

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))
}

如果您的查询是 JSON 查询,请将“ text/plain”替换为“”。application/json

于 2014-11-20T08:07:59.657 回答