How to make http request in golang?

Member

by schuyler , in category: Golang , 2 years ago

How to make http request in golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@schuyler you can use http package to make GET/POST or any other request in Golang, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

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

func main() {
   url := "https://devhubby.com/api/thread/latest"
   // Make GET http request to server
   res, err := http.Get(url)
   if err != nil {
      panic(err)
   }

   defer res.Body.Close()

   // Read response body
   body, err := ioutil.ReadAll(res.Body)
   if err != nil {
      panic(err)
   }

   fmt.Println(string(body))
   // Output: 200
   fmt.Println(res.StatusCode)
}

Member

by ward , 10 months ago

@schuyler 

In Golang, you can make HTTP requests using the built-in net/http package. Here are the steps to make an HTTP GET request:

  1. Import the net/http package:
1
import "net/http"


  1. Create an http.Client object:
1
client := &http.Client{}


  1. Create an http.Request object with the desired HTTP method, URL, and optional data payload:
1
req, err := http.NewRequest("GET", "https://example.com", nil)


  1. Optionally, add headers to the request:
1
req.Header.Add("Authorization", "Bearer MyAccessToken")


  1. Send the request using the http.Client object and get the response:
1
resp, err := client.Do(req)


  1. Optionally, read the response body:
1
2
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()


Here is an example of a complete HTTP GET request function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func httpRequest(url string) (string, error) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return "", err
    }
    // Optional headers
    req.Header.Add("Authorization", "Bearer MyAccessToken")

    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }

    return string(body), nil
}