How to Make HTTP Requests (GET / POST) in Golang

To make HTTP requests in Go, you can use the net/http” package from the standard library. You will make a GET request using the default Go HTTP client. Then, you will enhance your program to make a POST request with a body.

GET requests

To make a GET request, you can use the “http.Get()” function. The function takes a URL as an argument and returns an HTTP response and an error.

Example

package main

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

func main() {
  url := "https://jsonplaceholder.typicode.com/posts/1"
  resp, err := http.Get(url)

  if err != nil {
    log.Fatalf("Error making HTTP request: %v", err)
  }
  defer resp.Body.Close()

  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    log.Fatalf("Error reading response body: %v", err)
  }

  fmt.Println("Status code:", resp.StatusCode)
  fmt.Println("Response body:", string(body))
}

Output

Status code: 200
Response body: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et"
}

POST requests

To make a POST request, you can use the “http.Post()” function. This function takes a URL, content type, and an “io.Reader” representing the request body as arguments and returns an “*http.Response” and an error.

Example

package main

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

func main() {
  url := "https://jsonplaceholder.typicode.com/posts"
  data := []byte(`{"title": "Hello, World!", 
                   "body": "This is a test post.",
                   "userId": 1}`)

  resp, err := http.Post(url, "application/json", bytes.NewReader(data))
  if err != nil {
    log.Fatalf("Error making HTTP request: %v", err)
  }
  defer resp.Body.Close()

  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    log.Fatalf("Error reading response body: %v", err)
  }

  fmt.Println("Status code:", resp.StatusCode)
  fmt.Println("Response body:", string(body))
}

Output

Status code: 201
Response body: {
  "title": "Hello, World!",
  "body": "This is a test post.",
  "userId": 1,
  "id": 101
}

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.