Http (curl) request in golang

In the recent past, I got a chance to work on GO lang. The project on which I was working on, had a requirement of calling an external server. So I did that with the help of Go’s default HTTP client. Or in a more familiar word, this is kind of cURL for Go lang. You can find more in-depth information on Go’s default HTTP client from here.

This is a short post just to provide a tip, and I thought this is worth sharing. For this post, I assume you are familiar with Go lang and if you looking for how to do Http (curl) request in GO lang, then this post might help you. Here for mock JSON response, I am using https://reqres.in.




 

The Http (curl) request in golang:

1. The GET Request:

So let’s start with simple GET request. Create server.go file and write down the below code.

server.go:

Explanation:

let’s start with the main function,

  • In the main func, first I have created a variable named a url which holds the URL for the request.
  • After that, we will call NewRequest function from Package http and the result from that function is stored into req.
  • The http.DefaultClient.Do() will send an HTTP request and returns an HTTP response.
  • .Close() will immediately closes all active net.Listeners and any connections which are in state StateNew, StateIdle or StateActive.
  • Now we will use ioutil package, here we will call ReadAll function from this package. This function will read all the data from res.Body until an error or EOF occurs and at the end returns the data it reads.
  • In the line we will call Println() function from the package fmt.

2. let’s add HEADER to the Request:

Now let’s make a request with HEADER. Here all we will add a simple header just demonstrate how to add headers in http request in GO lang.

server.go:

Explanation:

In the above code, the highlighted line shows how to add a header in the request and the rest of the explanation is same as above.

3. The POST Request:

Now let’s make http request with POST method. In this request, we will parameters along with request with some request header. So let’s take a look at below code,

server.go:

Explanation:

As shown you can in the highlighted line, I have created a variable named as payload which holds the data which we will send with the http request.

And in The below line, I have replaced the GET with the POST, as this request will be in POST method. In the last parameter, we have passed the payload variable instead of nil.
And the rest of the code is same so as an explanation.

For this post that’s it. I hope you have found this post helpful. Happy GOing.