go.astrophena.name/base Module
Base Go packages for my projects.
package request
import "go.astrophena.name/base/request"
Package request provides utilities for making HTTP requests.
Index
Examples
Variables
var DefaultClient = &http.Client{ Timeout: 10 * time.Second, }
DefaultClient is a http.Client with nice defaults.
Functions
func Make
func Make[Response any](ctx context.Context, p Params) (Response, error)
Make makes a HTTP request with the provided parameters and unmarshals the response body into the specified type.
It supports JSON or URL-encoded format for request bodies and JSON for
request responses.
Example
package main
import (
"context"
"log"
"net/http"
"go.astrophena.name/base/request"
)
func main() {
type response struct {
OK bool `json:"ok"`
Checks map[string]struct {
Status string `json:"status"`
OK bool `json:"ok"`
} `json:"checks"`
}
// Checking health of Starlet.
health, err := request.Make[response](context.Background(), request.Params{
Method: http.MethodGet,
URL: "https://bot.astrophena.name/health",
})
if err != nil {
log.Fatal(err)
}
if health.OK {
log.Println("Alive.")
} else {
log.Printf("Not alive: %+v", health)
}
}
Example (Scrub)
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"go.astrophena.name/base/request"
)
func main() {
// Making request to GitHub API, scrubbing token out of error messages.
user, err := request.Make[map[string]any](context.Background(), request.Params{
Method: http.MethodGet,
URL: "https://api.github.com/user",
Headers: map[string]string{
"Authorization": "Bearer " + os.Getenv("GITHUB_TOKEN"),
},
Scrubber: strings.NewReplacer(os.Getenv("GITHUB_TOKEN"), "[EXPUNGED]"),
})
if err != nil {
log.Fatal(err)
}
fmt.Println(user["login"])
}
Types
type Params
type Params struct { // Method is the HTTP method (GET, POST, etc.) for the request. Method string // URL is the target URL of the request. URL string // Headers is a map of key-value pairs for additional request headers. Headers map[string]string // Body is any data to be sent in the request body. It will be marshaled to // JSON or, if it's type is url.Values, as query string with Content-Type // header set to "application/x-www-form-urlencoded". Body any // HTTPClient is an optional custom HTTP client object to use for the request. // If not provided, DefaultClient will be used. HTTPClient *http.Client // Scrubber is an optional strings.Replacer that scrubs unwanted data from // error messages. Scrubber *strings.Replacer }
Params defines the parameters needed for making an HTTP request.