fetch

package module
v0.5.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 9, 2026 License: Apache-2.0 Imports: 9 Imported by: 27

README

[fetch] -- Fetch Data from URL

ci status codeql status GitHub license GitHub release

fetch is a focused helper package for downloading data from URL endpoints. It wraps common net/http idioms so callers can handle download flows with less boilerplate and safer defaults.

Design goals

  • Keep application code simple for one-shot data fetching.
  • Hide repetitive net/http handling patterns.
  • Keep API surface small and composable.
  • Use context.Context based operations as the default style.

Development

Requirements
  • Go 1.25 or later
  • Task command (local tool for this repository)
Local validation
task test
task govulncheck

Run all maintenance tasks:

task

CI Workflows

  • ci: lint (golangci-lint with gosec), tests, and govulncheck
  • CodeQL: scheduled and push/PR static analysis

Usage

Install and import
go get github.com/goark/fetch@latest
import "github.com/goark/fetch"
Sample programs

All sample files under sample/ use the run build tag.

go run -tags run ./sample/sample.go
GET request
package main

import (
  "context"
  "fmt"
  "io"
  "os"

  "github.com/goark/fetch"
)

func main() {
  u, err := fetch.URL("https://github.com/spiegel-im-spiegel.gpg")
  if err != nil {
    fmt.Fprintln(os.Stderr, err)
    return
  }

  resp, err := fetch.New().GetWithContext(context.Background(), u)
  if err != nil {
    fmt.Fprintln(os.Stderr, err)
    return
  }
  defer resp.Close()

  if _, err := io.Copy(os.Stdout, resp.Body()); err != nil {
    fmt.Fprintln(os.Stderr, err)
  }
}
POST request
payload := strings.NewReader("name=alice")
resp, err := fetch.New().PostWithContext(ctx, u, payload,
  fetch.WithRequestHeaderSet("Content-Type", "application/x-www-form-urlencoded"),
)
if err != nil {
  return err
}
defer resp.Close()
Public API
  • fetch.URL(raw string) parses and validates URL input.
  • fetch.New(opts ...fetch.ClientOpts) creates a fetch client.
  • Client.GetWithContext(ctx, u, opts...) performs GET request.
  • Client.PostWithContext(ctx, u, payload, opts...) performs POST request.
  • fetch.WithHTTPClient(cli) injects custom *http.Client.
  • fetch.WithRequestHeaderAdd(name, value) and fetch.WithRequestHeaderSet(name, value) apply request headers.
Error handling

The package wraps errors, so use errors.Is for checks against:

  • fetch.ErrInvalidURL
  • fetch.ErrInvalidRequest
  • fetch.ErrHTTPStatus
if err != nil {
  switch {
  case errors.Is(err, fetch.ErrInvalidURL):
    // invalid URL input
  case errors.Is(err, fetch.ErrHTTPStatus):
    // non-success HTTP status (>= 400)
  }
}
Response lifecycle

Always close the response:

  • defer resp.Close() for streaming use.
  • Use resp.DumpBodyAndClose() when you need body bytes at once.
Modules Requirement Graph

dependency.png

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNullPointer indicates a nil receiver or nil embedded value access.
	ErrNullPointer = errors.New("null reference instance")
	// ErrInvalidRequest indicates a request construction or execution failure.
	ErrInvalidRequest = errors.New("invalid HTTP request")
	// ErrInvalidURL indicates an invalid URL input.
	ErrInvalidURL = errors.New("invalid URL")
	// ErrHTTPStatus indicates non-success HTTP status.
	ErrHTTPStatus = errors.New("bad HTTP status")
)

Functions

func URL

func URL(rawURL string) (*url.URL, error)

URL parses rawURL and returns *url.URL.

Leading and trailing whitespaces are trimmed before parsing.

Types

type Client

type Client interface {
	// Get sends a GET request.
	// Deprecated: Use GetWithContext instead.
	Get(u *url.URL, opts ...RequestOpts) (Response, error)
	// GetWithContext sends a GET request with context.
	GetWithContext(ctx context.Context, u *url.URL, opts ...RequestOpts) (Response, error)
	// Post sends a POST request.
	// Deprecated: Use PostWithContext instead.
	Post(u *url.URL, payload io.Reader, opts ...RequestOpts) (Response, error)
	// PostWithContext sends a POST request with context.
	PostWithContext(ctx context.Context, u *url.URL, payload io.Reader, opts ...RequestOpts) (Response, error)
}

Client represents a fetch client.

func New

func New(opts ...ClientOpts) Client

New creates a new Client.

type ClientOpts

type ClientOpts func(*client)

ClientOpts configures a Client.

func WithHTTPClient

func WithHTTPClient(cli *http.Client) ClientOpts

WithHTTPClient sets the HTTP client used by fetch.

If cli is nil, it falls back to a default *http.Client.

type RequestOpts

type RequestOpts func(*http.Request) *http.Request

RequestOpts applies options to an HTTP request.

The returned request value allows option functions to replace the request, for example when changing context with req.WithContext.

func WithContext

func WithContext(ctx context.Context) RequestOpts

WithContext sets request context on an option-applied request. Deprecated: Use GetWithContext and PostWithContext instead.

func WithRequestHeaderAdd

func WithRequestHeaderAdd(name, value string) RequestOpts

WithRequestHeaderAdd returns function for adding request header in http.Request.

func WithRequestHeaderSet

func WithRequestHeaderSet(name, value string) RequestOpts

WithRequestHeaderSet returns function for setting request header in http.Request.

type Response

type Response interface {
	// Request returns the original request.
	Request() *http.Request
	// Header returns response headers.
	Header() http.Header
	// Body returns the response body reader.
	Body() io.ReadCloser
	// Close drains and closes the response body.
	Close() error
	// DumpBodyAndClose reads all body bytes and closes the response body.
	DumpBodyAndClose() ([]byte, error)
}

Response wraps an HTTP response.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL