duanrenchuo9244 2014-11-20 08:00
浏览 65
已采纳

转到net / http请求

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条回答 默认 最新

  • duanpang5583 2014-11-20 08:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题