dongliming2416 2015-03-31 21:46
浏览 180
已采纳

Golang JSON / HTTP请求,例如curl

I am looking for a quick tutorial on how to perform requests with Golang that emulate those one would use with curl. I have two APIs that I want to communicate with that both essentially work the same way. One is ElasticSearch, the other is Phillips Hue. I know that both of these have libraries in Go. That's not what I'm after, I'm trying to learn how to do this:

$ curl -XGET 'http://localhost:9200/twitter/tweet/_search' -d '{
"query" : {
    "term" : { "user" : "kimchy" }
} }'

With Golang. Everything I can find people seem to be hard coding to

http://url:port/api/_function?something=value?anotherthing=value...

But I already have JSON objects floating around in the software. Is there a way that I can emulate the -d feature of CURL with a JSON string or struct or something similar?

  • 写回答

1条回答 默认 最新

  • douxian3170 2015-03-31 22:37
    关注

    As commenter @JimB pointed out, doing a GET request with a body is not disallowed by the HTTP/1.1 specification; however, it is also not required that servers actually parse the body, so do not be surprised if you encounter strange behavior.

    That said, here is how you would perform a GET request with a body using a golang HTTP client:

    reader := strings.NewReader(`{"body":123}`)
    request, err := http.NewRequest("GET", "http://localhost:3030/foo", reader)
    // TODO: check err
    client := &http.Client{}
    resp, err := client.Do(request)
    // TODO: check err
    

    The web server will see a request like this:

    GET /foo HTTP/1.1
    Host: localhost:3030
    User-Agent: Go 1.1 package http
    Content-Length: 12
    Accept-Encoding: gzip
    
    {"body":123}
    

    To build a command-line tool like "curl" you will need to use a number of go packages (e.g. for flag parsing and HTTP request handling) but presumably you can find what you need from the (excellent) docs.

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

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用