remote

package module
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2023 License: Apache-2.0 Imports: 10 Imported by: 8

README

REMOTE 🏝

GoDoc Version Build Status Go Report Card Codecov

Crazy Simple, Chainable HTTP Client for Go

Remote is a paper-thin wrapper on top of Go's HTTP library, that gives you sensible defaults, a pretty API with some modern conveniences, and full control of your HTTP requests. It's the fastest and easiest way to make an HTTP call using Go.

Inspired by Brandon Romano's Wrecker. Thanks Brandon!

How to Get data from an HTTP server
// Structure to read remote data into
users := []struct {
    ID string
    Name string
    Username string
    Email string
}{}

// Get data from a remote server
remote.Get("https://jsonplaceholder.typicode.com/users").
    Result(users, nil).
    Send()

How to Post/Put/Patch/Delete data to an HTTP server
// Data to send to the remote server
user := map[string]string{
    "id": "ABC123",
    "name": "Sarah Connor",
    "email": "sarah@sky.net",
}

// Structure to read response into
response := map[string]string{}

// Post data to the remote server (use your own URL)
remote.Post("https://example.com/post-service").
    JSON(user). // encode the user object into the request body as JSON
    Result(response, nil). // parse response (or error) into a data structure
    Send()
Handling HTTP Errors

Web services represent errors in a number of ways. Some simply return an HTTP error code, while others return complex data structures in the response body. REMOTE works with each style of error handling, so that your app always has the best information to work from.

// Structure to read successful response into.  This format is specific to the HTTP service.
success := struct{Name: string, Value: string, Comment: string}

// Structure to read failed response data into.  This format is specific to the HTTP service.
failure := struct(Code: int, Reason: string, StackTrace: string)

transaction := remote.Get("https://example.com/service-that-might-error").
    .Result(&success, &failure)

// Transaction returns an error **IF** the HTTP response code is not successful (200-299)
if err := transaction.Send(); err != nil {
    // Handle errors here.
    // `failure` variable will be populated with data from the remote service
    return
}

// Fall through to here means that the transaction was successful.  
// `success` variable will be populated with data from the remote service.

Middleware

Middleware allows you to modify a request before it is sent to the remote server, or modify the response after it is returned by the remote server. Each middleware object includes three hooks

Included Middleware
// AUTHORIZATION adds a simple "Authorization" header to your request
remote.Get("https://jsonplaceholder.typicode.com/users").
    Use(middleware.Authorization(myAuthorizationKey)).
    Result(users, nil).
    Send()
// BASIC AUTH adds a Base64 encoded "Authorization" header to your request,
// which follows the basic authorization standard
remote.Get("https://jsonplaceholder.typicode.com/users").
    Use(middleware.BasicAuth(username, password)).
    Result(users, nil).
    Send()
// DEBUG prints debugging statements to the console
remote.Get("https://jsonplaceholder.typicode.com/users").
    Use(middleware.Debug()).
    Result(users, nil).
    Send()
// OPAQUE makes direct changes to the URL string.
remote.Get("https://jsonplaceholder.typicode.com/users").
    Use(middleware.Opaque(opaqueURLStringHere)).
    Result(users, nil).
    Send()
Writing Custom Middleware

It's easy to write additional, custom middleware for your project. Just follow the samples in the /middleware folder, and pass in any object that follows the Middleware interface.

Config(*Transaction) allows you to change the transaction configuration before it is compiled into an HTTP request. This is typically the simplest, and easiest way to modify a request

Request(*http.Request) allows you to modify the raw HTTP request before it is sent to the remote server. This is useful in the rare cases when you need to make changes to a request that this library doesn't support.

Response(*http.Response) allows you to modify the raw HTTP response before its results are parsed and returned to the caller.

Pull Requests Welcome

Original versions of this library have been used in production on commercial applications for years, and have helped speed up development for everyone involved.

I'm now open sourcing this library, and others, with hopes that you'll also benefit from an easy HTTP library.

Please use GitHub to make suggestions, pull requests, and enhancements. We're all in this together! 🏝

Documentation

Overview

Package remote provides a simple and clean API for making HTTP requests to remote servers.

Package remote provides a simple and clean API for making HTTP requests to remote servers.

Index

Constants

View Source
const Accept = "Accept"

Accept is the string used in the HTTP header to request a response be encoded as a MIME type

View Source
const ContentType = "Content-Type"

ContentType is the string used in the HTTP header to designate a MIME type

View Source
const ContentTypeActivityPub = "application/activity+json"

ContentTypeActivityPub is the standard MIME type for ActivityPub content

View Source
const ContentTypeForm = "application/x-www-form-urlencoded"

ContentTypeForm is the standard MIME Type for Form encoded content

View Source
const ContentTypeHTML = "text/html"

ContentTypeHTML is the standard MIME type for HTML content

View Source
const ContentTypeJSON = "application/json"

ContentTypeJSON is the standard MIME Type for JSON content

View Source
const ContentTypeJSONFeed = "application/feed+json"

ContentTypeJSONFeed is the standard MIME Type for JSON Feed content https://en.wikipedia.org/wiki/JSON_Feed

View Source
const ContentTypeJSONLD = "application/ld+json"

ContentTypeJSONLD is the standard MIME Type for JSON-LD content https://en.wikipedia.org/wiki/JSON-LD

View Source
const ContentTypeJSONResourceDescriptor = "application/jrd+json"

ContentTypeJSONResourceDescriptor is the standard MIME Type for JSON Resource Descriptor content which is used by WebFinger: https://datatracker.ietf.org/doc/html/rfc7033#section-10.2

View Source
const ContentTypePlain = "text/plain"

ContentTypePlain is the default plaintext MIME type

View Source
const ContentTypeXML = "application/xml"

ContentTypeXML is the standard MIME Type for XML content

Variables

This section is empty.

Functions

This section is empty.

Types

type ErrorReport

type ErrorReport struct {
	URL     string `json:"url"`
	Request struct {
		Method string            `json:"method"`
		Header map[string]string `json:"header"`
		Body   string            `json:"body"`
	} `json:"request"`
	Response struct {
		StatusCode int         `json:"statusCode"`
		Status     string      `json:"status"`
		Header     http.Header `json:"header"`
		Body       string      `json:"body"`
	} `json:"response"`
}

ErrorReport includes all the data returned by a transaction if it throws an error for any reason.

type Middleware

type Middleware struct {
	Config   func(*Transaction) error            // Config is executed on the Transaction, before it is compiled into an http.Request object
	Request  func(*http.Request) error           // Request is executed on the http.Request, before it is sent to the remote server
	Response func(*http.Response, *[]byte) error // Response is executed on the http.Response, before it is parsed into a success or failure object.
}

Middleware is a decorator that can modify the request before it is sent to the remote HTTP server, or modify the response after it is returned by the remote HTTP server.

type Transaction

type Transaction struct {
	Client         *http.Client      // HTTP client to use to execute the request.  This may be overridden or updated by the calling program.
	Method         string            // HTTP method to use when sending the request
	URLValue       string            // URL of the remote server to call
	HeaderValues   map[string]string // HTTP Header values to send in the request
	QueryString    url.Values        // Query String to append to the URL
	FormData       url.Values        // (if set) Form data to pass to the remote server as x-www-form-urlencoded
	BodyObject     any               // Other data to send in the body.  Encoding determined by header["Content-Type"]
	SuccessObject  any               // Object to parse the response into -- IF the status code is successful
	FailureObject  any               // Object to parse the response into -- IF the status code is NOT successful
	Middleware     []Middleware      // Middleware to execute on the request/response
	RequestObject  *http.Request     // HTTP request that is delivered to the remote server
	ResponseObject *http.Response    // HTTP response that is returned from the remote server
}

Transaction represents a single HTTP request/response to a remote HTTP server.

func Delete

func Delete(url string) *Transaction

Delete creates a new HTTP request to the designated URL, using the DELETE method.

func Get

func Get(url string) *Transaction

Get creates a new HTTP request to the designated URL, using the GET method

func Patch

func Patch(url string) *Transaction

Patch creates a new HTTP request to the designated URL, using the PATCH method

func Post

func Post(url string) *Transaction

Post creates a new HTTP request to the designated URL, using the POST method

func Put

func Put(url string) *Transaction

Put creates a new HTTP request to the designated URL, using the PUT method

func (*Transaction) Accept added in v0.10.1

func (t *Transaction) Accept(contentTypes ...string) *Transaction

Accept sets the Content-Type header of the HTTP request.

func (*Transaction) Body

func (t *Transaction) Body(value string) *Transaction

Body sets the request body, to be encoded as plain text

func (*Transaction) ContentType

func (t *Transaction) ContentType(value string) *Transaction

ContentType sets the Content-Type header of the HTTP request.

func (*Transaction) ErrorReport

func (t *Transaction) ErrorReport() ErrorReport

ErrorReport generates a data dump of the current state of the HTTP transaction. This is used when reporting errors via derp, to provide insights into what went wrong.

func (*Transaction) Form

func (t *Transaction) Form(name string, value string) *Transaction

Form adds a name/value pair to the form data to be sent to the remote server.

func (*Transaction) Header

func (t *Transaction) Header(name string, value string) *Transaction

Header sets a designated header value in the HTTP request.

func (*Transaction) IsContentTypeEmpty added in v0.10.1

func (t *Transaction) IsContentTypeEmpty() bool

func (*Transaction) JSON

func (t *Transaction) JSON(value any) *Transaction

JSON sets the request body, to be encoded as JSON.

func (*Transaction) Query

func (t *Transaction) Query(name string, value string) *Transaction

Query sets a name/value pair in the URL query string.

func (*Transaction) Response

func (t *Transaction) Response(success any, failure any) *Transaction

Response sets the objects for parsing HTTP success and failure responses

func (*Transaction) Send

func (t *Transaction) Send() error

Send executes the transaction, sending the request to the remote server.

func (*Transaction) Use

func (t *Transaction) Use(middleware ...Middleware) *Transaction

Use lets you add middleware to the transaction. Middleware is able to modify transaction data before and after it is sent to the remote server.

func (*Transaction) XML

func (t *Transaction) XML(value any) *Transaction

XML sets the request body, to be encoded as XML.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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