In our previous tutorial, we have explained about Channels in Golang. In this tutorial, we will explain how to make HTTP Requests in Golang.
There are net/http
package is available to make HTTP requests. We just need tp import the package in our script and can use GET
, POST
, PostForm
HTTP functions to make requests.
So here in this tutorial we will explain how to make GET
, POST
, PostForm
HTTP requests in Golang.
Also, read:
We will cover following in this tutorial:
1. HTTP GET Request
We can make the simple HTTP GET request using http.Get
function. We will import the net/http
package and use http.Get
function to make request.
Here in this example, we will make the HTTP GET request and get response. We will read the response and display response output.
package main import ( "fmt" "io/ioutil" "net/http" ) func main() { response, err := http.Get("https://api.github.com/users/mojombo") if err != nil { print(err) } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) if err != nil { print(err) } fmt.Print(string(body)) }
Output:
{ "login":"mojombo", "id":1, "node_id":"MDQ6VXNlcjE=", "avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4", "gravatar_id":"", "url":"https://api.github.com/users/mojombo", "html_url":"https://github.com/mojombo", "followers_url":"https://api.github.com/users/mojombo/followers", "following_url":"https://api.github.com/users/mojombo/following{/other_user}", "gists_url":"https://api.github.com/users/mojombo/gists{/gist_id}", "starred_url":"https://api.github.com/users/mojombo/starred{/owner}{/repo}", "subscriptions_url":"https://api.github.com/users/mojombo/subscriptions", "organizations_url":"https://api.github.com/users/mojombo/orgs", "repos_url":"https://api.github.com/users/mojombo/repos", "events_url":"https://api.github.com/users/mojombo/events{/privacy}", "received_events_url":"https://api.github.com/users/mojombo/received_events", "type":"User", "site_admin":false, "name":"Tom Preston-Werner", "company":null, "blog":"http://tom.preston-werner.com", "location":"San Francisco", "email":null, "hireable":null, "bio":null, "twitter_username":null, "public_repos":61, "public_gists":62, "followers":22047, "following":11, "created_at":"2007-10-20T05:24:19Z", "updated_at":"2020-07-07T16:50:36Z" }
2. HTTP POST Request
We need to import the net/http
package for making HTTP request. Then we can use the http.Post
function to make HTTP POST requests.
Here in this example, we will make HTTP POST request to https://httpbin.org/post
website and send the JSON payload. We will marsh marshaling a map and will get the []byte if successful request. We will handle the error and then make POST request using http.Post
. Then we will read the response and display.
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { requestBody, error := json.Marshal(map[string]string{ "username": "webdamn go", "email": "webdamngo@gmail.com", }) if error != nil { print(error) } response, error := http.Post("https://httpbin.org/post", "application/json", bytes.NewBuffer(requestBody)) if error != nil { print(error) } defer response.Body.Close() body, error := ioutil.ReadAll(response.Body) if error != nil { print(error) } fmt.Println(string(body)) }
Output:
{ "args": {}, "data": "{\"email\":\"webdamngo@gmail.com\",\"username\":\"webdamn go\"}", "files": {}, "form": {}, "headers": { "Accept-Encoding": "gzip", "Content-Length": "55", "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "Go-http-client/2.0", "X-Amzn-Trace-Id": "Root=1-5f13c0b8-5bac0cd4e6ebe3d08489fe24" }, "json": { "email": "webdamngo@gmail.com", "username": "webdamn go" }, "origin": "47.8.250.54", "url": "https://httpbin.org/post" }
3. HTTP Posting Form Data
We need import the net/http
package for making HTTP request to post form data. Then we can use the http.PostForm
function to post form data.
Here in this example, we will create form data variable formData
is of url.Values type, which is map[string][]string
that’s a map type, where each key has a value of []string. For each key, we can have the list of string values. Then we will use the http.PostForm
to submit form values to https://httpbin.org/post
url and display form data value.
package main import ( "encoding/json" "log" "net/http" "net/url" ) func main() { MakeRequest() } func MakeRequest() { formData := url.Values{ "name": {"webdamn"}, } response, error := http.PostForm("https://httpbin.org/post", formData) if error != nil { log.Fatalln(error) } var result map[string]interface{} json.NewDecoder(response.Body).Decode(&result) log.Println(result["form"]) }
Output:
2020/07/19 09:29:03 map[name:webdamn]
Conclusion
In this tutorial we have explained how to make HTTP GET, POST requests using Go. We have also explained how to post form data. If you have any queries regarding this tutorial, then please feel free to let me know in the comments section below.
You may also like:
- Regular Expressions in Golang
- Creating REST API with Golang
- How to Delete Files in Golang
- Working with Structs in Golang
- Working with Date and Time in Golang
- Working with Channels in Golang
- Concurrency with Goroutines in Golang
- Working with Maps in Golang
- Marshalling and Unmarshalling in Golang
- AWS S3 File Upload in Golang
- Write Data to CSV File using Golang
- How to Read CSV File using Golang
- Parsing JSON Data using Golang
- Read File Line by Line using Golang