去网/ http请求 [英] Go net/http request
本文介绍了去网/ http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮助我将Ruby代码转换为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)}
转到Go。
推荐答案
您似乎想要发布一个查询,这将是类似的对此答案:
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))
}
替换 text / plain
与 application / json
,如果您的查询是JSON文件。
Replace "text/plain
" with "application/json
" if your query is a JSON one.
这篇关于去网/ http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文