Golang JSON / HTTP request such as curl

I am looking for a quick tutorial on how to execute queries with Golang that emulate those that will be used with curl. I have two APIs that I want to communicate with, and they essentially work the same way. One of them is ElasticSearch, the other is Phillips Hue. I know that both have libraries in Go. This is not what I need, I'm trying to learn this:

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

With the Golan. All I can find seems to be that hard coding

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

But I already have JSON objects floating in the software. Is there a way that I can emulate the -d CURL function using a string or JSON structure or something similar?

+7
json curl go
source share
1 answer

As @JimB commentator noted, executing a GET request with a body is not prohibited by the HTTP / 1.1 specification; however, it is also not required that the servers actually analyze the body, so do not be surprised if you encounter strange behavior.

So, here is how you will execute the GET request with the body using the 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 this request:

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

To create a command line tool such as "curl", you will need to use several go packages (for example, to parse flags and process HTTP requests ), but presumably you can find what you need (excellent) docs for.

+16
source

All Articles