Sling Academy
Home/Golang/Making HTTP Requests with the `net/http` Package

Making HTTP Requests with the `net/http` Package

Last updated: November 27, 2024

In this article, we'll explore how to make HTTP requests using the net/http package in Go, one of the most widely used packages for handling HTTP operations. Understanding how to make such requests is vital for interacting with APIs, fetching web content, and more.

Introduction to the net/http Package

The net/http package in Go is comprehensive and provides many functions and methods for HTTP clients and servers. In this discussion, we will focus on its client capabilities.

Performing a Simple GET Request

A GET request is one of the most common HTTP requests. Let's see how it can be done:

package main

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

func main() {
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

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

This code snippet demonstrates how to perform a simple GET request and print the response body to the console.

Sending a POST Request

To send data to a server, you use a POST request. The example below shows how to perform a POST request with JSON data.

package main

import (
    "bytes"
    "fmt"
    "net/http"
)

func main() {
    jsonStr := []byte(`{"title":"foo","body":"bar","userId":1}`)
    resp, err := http.Post("https://jsonplaceholder.typicode.com/posts", "application/json", bytes.NewBuffer(jsonStr))
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    fmt.Println("Response status:", resp.Status)
}

This code snippet shows how to send JSON data in the body of a POST request.

Customizing Requests Using http.Client

For more control over your HTTP requests, use http.Client. It allows specifying request headers, timeouts, etc.

package main

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

func main() {
    client := &http.Client{
        Timeout: 10 * time.Second,
    }
    req, err := http.NewRequest("GET", "https://jsonplaceholder.typicode.com/posts/1", nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    req.Header.Set("User-Agent", "MyCustomUserAgent/1.0")

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

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

In the above code, method http.NewRequest gives more flexibility in crafting an HTTP request. We can add a custom header as shown.

Conclusion

The net/http package is a powerful tool for making HTTP requests in Go. With its ability to handle different request types and customize them using the http.Client, you can interact with APIs and web services efficiently.

Next Article: Handling WebSocket Connections in Go

Previous Article: Understanding Context for Request Management in Go

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant