Minimalistic REST client for Go applications

RClient

MIT License Go Report Card Go Doc

Getting Started

Checkout the Examples folder for some working examples. The following snippet shows RClient interacting with Github's API:

package main

import (
        "github.com/zpatrick/rclient"
        "log"
)

type Repository struct {
        Name        string `json:"name"`
}

func main() {
        client := rclient.NewRestClient("https://api.github.com")

        var repos []Repository
        if err := client.Get("/users/zpatrick/repos", &repos); err != nil {
                log.Fatal(err)
        }

        log.Println(repos)
}

Request Options

Requests can be configured using a Request Option. A RequestOption is simply a function that manipulates an http.Request. You can create request options like so:

setProto := func(req *http.Request) error {
    req.Proto = "HTTP/1.0"
    return nil
}

client.Get("/path", &v, setProto)

The built-in request options are described below.

Header / Headers

The Header() and Headers() options add header(s) to a *http.Request.

// add a single header
client.Get("/path", &v, rclient.Header("name", "val"))

// add multiple headers
client.Get("/path", &v, rclient.Header("name1", "val1"), rclient.Header("name2", "val2"))
client.Get("/path", &v, rclient.Headers(map[string]string{"name1": "val1", "name2":"val2"}))

Basic Auth

The BasicAuth() option adds basic auth to a *http.Request.

client.Get("/path", &v, rclient.BasicAuth("user", "pass"))

Query

The Query() options adds a query to a *http.Request.

query := url.Values{}
query.Add("name", "John")
query.Add("age", "35")

client.Get("/path", &v, rclient.Query(query))

NOTE: This can also be accomplished by adding the raw query to the path argument

client.Get("/path?name=John&age=35", &v)

Client Configuration

The RestClient can be configured using the Client Options described below.

Doer

The Doer() option sets the RequestDoer field on the RestClient. This is the http.DefaultClient by default, and it can be set to anything that satisfies the RequestDoer interface.

client, err := rclient.NewRestClient("https://api.github.com", rclient.Doer(&http.Client{}))

Request Options

The RequestOptions() option sets the RequestOptions field on the RestClient. This will manipulate each request made by the RestClient. This can be any of the options described in the Request Options section. A typical use-case would be adding headers for each request.

options := []rclient.RequestOption{
    rclient.Header("name", "John Doe").
    rclient.Header("token", "abc123"),
}

client, err := rclient.NewRestClient("https://api.github.com", rclient.RequestOptions(options...))

Builder

The Builder() option sets the RequestBuilder field on the RestClient. This field is responsible for building *http.Request objects. This is the BuildJSONRequest function by default, and it can be set to any RequestBuilder function.

builder := func(method, url string, body interface{}, options ...RequestOption) (*http.Request, error){
    req, _ := http.NewRequest(method, url, nil)
    for _, option := range options {
		if err := option(req); err != nil {
			return nil, err
		}
	}
	
    return nil, errors.New("I forgot to add a body to the request!")
}

client, err := rclient.NewRestClient("https://api.github.com", rclient.Builder(builder))

Reader

The Reader() option sets the ResponseReader field on the RestClient. This field is responsible for reading *http.Response objects. This is the ReadJSONResponse function by default, and it can be set to any ResponseReader function.

reader := func(resp *http.Response, v interface{}) error{
    defer resp.Body.Close()
    return json.NewDecoder(resp.Body).Decode(v)
}

client, err := rclient.NewRestClient("https://api.github.com", rclient.Reader(reader))

License

This work is published under the MIT license.

Please see the LICENSE file for details.

Similar Resources

Retry, Race, All, Some, etc strategies for http.Client calls

reqstrategy Package reqstrategy provides functions for coordinating http.Client calls. It wraps typical call strategies like making simultaneous reque

Apr 30, 2021

An enhanced HTTP client for Go

An enhanced HTTP client for Go

Heimdall Description Installation Usage Making a simple GET request Creating a hystrix-like circuit breaker Creating a hystrix-like circuit breaker wi

Jan 2, 2023

fhttp is a fork of net/http that provides an array of features pertaining to the fingerprint of the golang http client.

fhttp The f stands for flex. fhttp is a fork of net/http that provides an array of features pertaining to the fingerprint of the golang http client. T

Jan 1, 2023

goql is a GraphQL client package written in Go. with built-in two-way marshaling support via struct tags.

goql is a GraphQL client package written in Go. with built-in two-way marshaling support via struct tags.

Dec 1, 2022

Go Supertest is minimalize HTTP Client Testing only for Gin Framework

Go Supertest is minimalize HTTP Client Testing only for Gin Framework, inspired by Supertest package library HTTP Client Testing for Express.js Framework.

May 22, 2022

Gotcha is an high level HTTP client with a got-like API

Gotcha is an high level HTTP client with a got-like API

Gotcha is an alternative to Go's http client, with an API inspired by got. It can interface with other HTTP packages through an adapter.

Dec 7, 2022

Declarative golang HTTP client

go-req Declarative golang HTTP client package req_test

Dec 20, 2022

simple mealie client

go-mealie A dirt simple go CLI client and badly written go library Enjoy this alpha release Config mealie can be configured using a yaml file or by us

Nov 27, 2022
Comments
  • Add http.Response to ReadJSONResponse error

    Add http.Response to ReadJSONResponse error

    The current error in ReadJSONResponse isn't very useful when trying to handle errors:

    return fmt.Errorf("Invalid status code: %d", resp.StatusCode)
    

    This should return a custom error type that has the http.Response as a public field.

  • readme should be less verbose

    readme should be less verbose

    Instead of going over each request/client option, I should have a slimmed down version in the readme and examples of each option in godoc, e.g.:

    # Request Options
    * [Header](#link-to-example) - Add a header to a request
    * [Basic Auth](#link-to-example) - Add basic auth  to a request
    
    # Client Options
    * [Doer](#) - Specify which object performs the http.Request (the default is http.DefaultClient)
    
    # Error Handling
    ## using rcilent.ResponseError
    ## using ResponseReader() option
    
  • error parsing should be easier

    error parsing should be easier

    Right now, you need to totally override the request reader if you want to read custom error types. It should be more simple to try and marshal into errors. Perhaps a request option:

    var resp int
    var myerr *MyCustomError
    client.Get("/path", &resp, rclient.Error(&myerr))
    

    Another option could map status codes to types:

    client.Get("/path", &resp, rclient.StatusMap(
        series.Ints(200, 299): &someType,
        series.Ints(400, 499): &someError,
        series.Ints(500, 599): &someOtherError,
    ))
    
An enhanced http client for Golang
An enhanced http client for Golang

go-http-client An enhanced http client for Golang Documentation on go.dev ?? This package provides you a http client package for your http requests. Y

Dec 23, 2022
An enhanced HTTP client for Go
An enhanced HTTP client for Go

Heimdall Description Installation Usage Making a simple GET request Creating a hystrix-like circuit breaker Creating a hystrix-like circuit breaker wi

Jan 9, 2023
Enriches the standard go http client with retry functionality.

httpRetry Enriches the standard go http client with retry functionality using a wrapper around the Roundtripper interface. The advantage of this libra

Dec 10, 2022
http client for golang
http client for golang

Request HTTP client for golang, Inspired by Javascript-axios Python-request. If you have experience about axios or requests, you will love it. No 3rd

Dec 18, 2022
A nicer interface for golang stdlib HTTP client

rq A nicer interface for golang stdlib HTTP client Documents rq: here client: here jar: here Why? Because golang HTTP client is a pain in the a... Fea

Dec 12, 2022
A Go HTTP client library for creating and sending API requests
A Go HTTP client library for creating and sending API requests

Sling Sling is a Go HTTP client library for creating and sending API requests. Slings store HTTP Request properties to simplify sending requests and d

Jan 7, 2023
a Go HTTP client with timeouts

go-httpclient requires Go 1.1+ as of v0.4.0 the API has been completely re-written for Go 1.1 (for a Go 1.0.x compatible release see 1adef50) Provides

Nov 10, 2022
GoRequest -- Simplified HTTP client ( inspired by nodejs SuperAgent )
GoRequest -- Simplified HTTP client ( inspired by nodejs SuperAgent )

GoRequest GoRequest -- Simplified HTTP client ( inspired by famous SuperAgent lib in Node.js ) "Shooting Requests like a Machine Gun" - Gopher Sending

Jan 1, 2023
Http client call for golang http api calls

httpclient-call-go This library is used to make http calls to different API services Install Package go get

Oct 7, 2022
gout to become the Swiss Army Knife of the http client @^^@---> gout 是http client领域的瑞士军刀,小巧,强大,犀利。具体用法可看文档,如使用迷惑或者API用得不爽都可提issues
gout to become the Swiss Army Knife of the http client @^^@--->  gout 是http client领域的瑞士军刀,小巧,强大,犀利。具体用法可看文档,如使用迷惑或者API用得不爽都可提issues

gout gout 是go写的http 客户端,为提高工作效率而开发 构架 feature 支持设置 GET/PUT/DELETE/PATH/HEAD/OPTIONS 支持设置请求 http header(可传 struct,map,array,slice 等类型) 支持设置 URL query(可

Dec 29, 2022