Skip to content
Go

HTTP Client

Send HTTP requests.

By EZ4Code Team
httpclient

Code

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"
)

func main() {
    client := &http.Client{Timeout: 10 * time.Second}

    // GET
    resp, _ := client.Get("https://api.github.com/users/golang")
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))

    // POST JSON
    payload, _ := json.Marshal(map[string]string{"key": "value"})
    resp2, _ := client.Post(
        "https://httpbin.org/post",
        "application/json",
        bytes.NewBuffer(payload),
    )
    defer resp2.Body.Close()
}

Explanation

http.Client sends requests; setting Timeout avoids permanent blocking.

More Go Snippets