Skip to content
 
 

Latest commit

 

History

31 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build status Quality Gate Status Go Report Card Go Reference License: Apache 2.0

Slinging HTTP

The httpsling library simplifies the way you make HTTP requests. It's intended to provide an easy-to-use interface for sending requests and handling responses, reducing the boilerplate code typically associated with the net/http package.

Overview

Creating a new Requester and making a request should be straightforward:

package main

import (
	"log"
	"net/http"

	"github.com/theopenlane/httpsling"
)

func main() {
	requester, err := httpsling.New(
		httpsling.Client(), // use the default sling client
		httpsling.URL("https://api.example.com"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Perform a GET request
	var out map[string]any
	resp, err := requester.Receive(&out, httpsling.Get("resource"))
	if err != nil {
		log.Fatal(err)
	}

	defer resp.Body.Close()

	log.Println(out)
}

Core Functions

// build just the request
Request(...Option) (*http.Request, error)
RequestWithContext(context.Context, ...Option) (*http.Request, error)

// build the request and send the request
Send(...Option) (*http.Response, error)
SendWithContext(context.Context, ...Option) (*http.Response, error)

// build and send the request and parse the response into a value
Receive(any, ...Option) (*http.Response, error)
ReceiveWithContext(context.Context, any, ...Option) (*http.Response, error)

// typed helper using generics
ReceiveInto[T any](...Option) (*http.Response, T, error)
ReceiveIntoWithContext[T any](context.Context, ...Option) (*http.Response, T, error)

// stream response body into an io.Writer
ReceiveTo(io.Writer, ...Option) (*http.Response, int64, error)
ReceiveToWithContext(context.Context, io.Writer, ...Option) (*http.Response, int64, error)

Configuring BaseURL

Set the base URL for all requests using the Requester option URL:

 httpsling.URL("https://api.example.com"),

Setting Headers

Set default headers for all requests, e.g. Bearer token Authorization

    requester.Apply(httpsling.BearerAuth("YOUR_ACCESS_TOKEN"))

Setting up CookieJar

Add a Cookie Jar to the default client:

    requester, err = httpsling.New(
        httpsling.Client(
            httpclient.CookieJar(nil), // Use a cookie jar to store cookies
        ),
    )
    if err != nil {
        return nil, err
    }

Configuring Timeouts

Define a global timeout for all requests to prevent indefinitely hanging operations:

    httpsling.Client(
        httpclient.Timeout(time.Duration(30*time.Second)),
    ),

TLS Configuration

Custom TLS configurations can be applied for enhanced security measures, such as loading custom certificates:

    httpsling.Client(
        httpclient.SkipVerify(true),
    ),

Requests

The library provides a Receive to construct and dispatch HTTP. Here are examples of performing various types of requests, including adding query parameters, setting headers, and attaching a body to your requests.

GET Request

    resp, err := requester.ReceiveWithContext(context.Background(), &out,
        httpsling.Get("/path"),
        httpsling.QueryParam("query", "meow"),
    )

POST Request

    resp, err := requester.ReceiveWithContext(context.Background(), &out,
        httpsling.Post("/path"),
        httpsling.Body(map[string]any{"key": "value"})
    )

PUT Request

    resp, err := requester.ReceiveWithContext(context.Background(), &out,
        httpsling.Put("/path/123456"),
        httpsling.Body(map[string]any{"key": "newValue"})
    )

DELETE Request

    resp, err := requester.ReceiveWithContext(context.Background(), &out,
        httpsling.Delete("/path/123456"),
    )

Authentication

Supports various authentication methods:

  • Basic Auth:
    requester.Apply(httpsling.BasicAuth("username", "superSecurePassword!"))
  • Bearer Token:
    requester.Apply(httpsling.BearerAuth("YOUR_ACCESS_TOKEN"))

Responses

Handling responses is necessary in determining the outcome of your HTTP requests - the library has some built-in response code validators and other tasty things.

type APIResponse struct {
    Data string `json:"data"`
}

var out APIResponse
resp, err := s.Requester.ReceiveWithContext(ctx, &out,
		httpsling.Post("/path"),
		httpsling.Body(in))

defer resp.Body.Close()

log.Printf("Status Code: %d\n", resp.StatusCode)
log.Printf("Response Data: %s\n", out.Data)

Note: Receive fully reads the response into memory to unmarshal, and restores resp.Body so it remains readable by callers.

Evaluating Response Success

To assess whether the HTTP request was successful:

  • IsSuccess: Check if the status code signifies a successful response
    if httpsling.IsSuccess(resp) {
        fmt.Println("The request succeeded hot diggity dog")
    }

Inspirations

This library was inspired by and built upon the work of several other HTTP client libraries:

Contributing

See contributing for details.

About

easy-to-use interface for sending http requests and handling responses

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages