HTTP Client in Go

Go: HTTP Client

The Go standard library provides the net/http package for making HTTP requests. Here's an example of how to use it to make a simple GET request:

    package main

    import (
        "fmt"
        "net/http"
    )

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

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

This code sends a GET request to the specified URL and prints the response status. The http.Get function returns a response object and an error, which we check for and handle accordingly. We also use the defer keyword to ensure that the response body is closed after we're finished using it.

How to add headers to your request in Go?

You can also add headers to your request by creating a http.Header object and setting values on it:

    package main

    import (
        "fmt"
        "net/http"
    )

    func main() {
        client := &http.Client{}

        req, err := http.NewRequest("GET", "https://jsonplaceholder.typicode.com/todos/1", nil)
        if err != nil {
            fmt.Println("Error:", err)
            return
        }

        req.Header.Set("User-Agent", "my-awesome-client")

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

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

This code creates a new http.Request object and sets the User-Agent header to a custom value. It then uses an http.Client object to send the request and get the response.

I hope that helps you get started with making HTTP requests in Go! Let me know if you have any more questions.

Previous Article

Next Article