• Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
No Result
View All Result

Http (curl) request in golang

by Shashank Tiwari
August 5, 2023
in GO lang
4
2 Minutes Read
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:

 /*
* Http (curl) request in golang
* @author Shashank Tiwari
*/
package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://reqres.in/api/users"

    req, _ := http.NewRequest("GET", url, nil)

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))

}

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 callPrintln() function from the packagefmt.

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:

 /*
* Http (curl) request in golang
* @author Shashank Tiwari
*/
package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://reqres.in/api/users"

    req, _ := http.NewRequest("GET", url, nil)

    req.Header.Add("cache-control", "no-cache")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))

}

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:

 /*
* Http (curl) request in golang
* @author Shashank Tiwari
*/
package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://reqres.in/api/users"

    payload := strings.NewReader("name=test&jab=teacher")

    req, _ := http.NewRequest("POST", url, payload)

    req.Header.Add("content-type", "application/x-www-form-urlencoded")
    req.Header.Add("cache-control", "no-cache")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))
}

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.

Tags: HTTPRequest Response
Previous Post

Integrating Ladda buttons in Angular 2

Next Post

Login template using Angular Material

Related Posts

Real time private chatting app using React, Golang and mongodb banner-part 2
GO lang

Real time private chatting app using GoLang, React and mongodb – Part 2

July 4, 2020
Real time private chatting app using React, Golang and mongodb banner
GO lang

Real time private chatting app using GoLang, React and Mongodb – Part 1

July 4, 2020
Sending message to specific user with GoLang WebSocket
GO lang

Sending message to specific user with GoLang WebSocket

August 6, 2023
Next Post
Login template using Angular Material

Login template using Angular Material

Comments 4

  1. mehmet says:
    7 years ago

    package main

    import (
    “fmt”
    “net/http”
    “io/ioutil”
    )

    func main() {

    url := “https://10.10.10.100:5464”

    req, _ := http.NewRequest(“GET”, url, nil)

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))

    }

    I did like this. My Url is ip and port no in my server.go file but I faced error “invalid memory address or nil pointer dereference ” what is the problem ? I can not send request to my server. Can you help me? Thank you.

  2. vaibhav goyal says:
    6 years ago

    How to make url dynamic?

    • Shashank Tiwari says:
      6 years ago

      You can move this code in some other function, then you can pass any string(URL).
      To make dynamic strings refer below link,
      https://stackoverflow.com/questions/29071212/implementing-dynamic-strings-in-golang

      Hope this helps,

  3. Migmam says:
    6 years ago

    In the post example you are missing import strings




https://codershood.info

www.codershood.info programming blog dedicated to providing high-quality coding tutorial and articles on web development, Angular, React, Laravel, AngularJs, CSS, Node.js, ExpressJs and many more. We also provide ebook based on complicated web application along with the source code.

  • Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.

No Result
View All Result
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.