Skip to content

HTTP Request

http.Get

Use http.Get for simple GET requests where you don't need to customize the headers extensively.

Example

run command
go run src/http/basic_http.go
package main

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

func main() {
    req, err := http.Get("https://www.google.com/")
    if err != nil {
        fmt.Println("Error requesting:", err)
        panic(err)
    }
    defer req.Body.Close()
    res, err := io.ReadAll(req.Body)
    if err != nil {
        fmt.Println("Error reading response:", err)
        panic(err)
    }
    fmt.Println(string(res))
}
output
GOOGLE PAGE IN STRING

http.Post

The http.Post function simplifies the process of sending POST requests. It allows you to specify the URL, the content type, and the request body. It's suitable for simple POST requests where you don't need to customize the headers extensively.

Example

run command
go run src/http/http_post.go
package main

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

func main() {
    payload := []byte(`{"key1": "value1", "key2": "value2"}`)
    body := bytes.NewBuffer(payload)

    resp, err := http.Post("https://httpbin.org/post", "application/json", body)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("Status:", resp.Status)
}
output
Status: 200 OK

http.Client

The http.Client object allows customization of the HTTP request behavior, such as setting timeouts, defining transport properties, and managing the client's behavior.

http.Client with a 3-second Timeout

run command
go run src/http/http_client.go
package main

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

func main() {
    client := http.Client{
        Timeout: time.Second * 3, // Set a timeout for the request
    }
    resp, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(body))
}
output
{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

http.NewRequest

This function creates a new HTTP request. It allows control over the request headers, methods, and request bodies. You can set custom headers, perform more type requests (such as PUT and DELETE), and attach a request body. It's particularly useful for making custom or more complex HTTP requests.

Post using Client and NewRequest

run command
go run src/http/http_newRequest.go
package main

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

func main() {
    payload := []byte(`{"key1": "value1", "key2": "value2"}`)
    body := bytes.NewBuffer(payload)

    req, err := http.NewRequest("POST", "https://httpbin.org/post", body)
    if err != nil {
        panic(err)
    }
    req.Header.Set("Content-Type", "application/json")
    client := http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("Status:", resp.Status)
}
output
Status: 200 OK

http.NewRequestWithContext

A function that creates a new HTTP request with a specific context. This function is particularly useful when you need to set a deadline, cancel a request, or pass a request-specific value across API boundaries.

Post using Client and NewRequestWithContext

run command
go run src/http/http_NewRequestWithContext.go
package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func main() {
    ctx := context.Background()
    ctx, cancel := context.WithTimeout(ctx, time.Second*5)
    defer cancel()

    req, err := http.NewRequestWithContext(ctx, "GET", "https://jsonplaceholder.typicode.com/posts/1", nil)
    if err != nil {
        panic(err)
    }

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println(resp.Status)
}
output
200 OK

Examples

  1. Get Address - Basic API