Go net/http 请求

huangapple go评论82阅读模式
英文:

Go net/http request

问题

有人可以帮我将我的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) }

转换为Go语言。

英文:

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.body =     query
 response =   Net::HTTP.new(host, post).start{|http http.request(request)}   

to Go.

答案1

得分: 23

您似乎想要发送一个POST请求,类似于这个答案:

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"

英文:

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.

huangapple
  • 本文由 发表于 2014年11月20日 16:00:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/27034517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定