英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论