Simple REST client library in Go

Overview

Simple REST client library in Go

Context

The goal was to make a minimal library that could be easily reused and expanded in other projects. It doesn't rely on any third-party modules except for mapstructure which is used in the test implementation. Neither does it feature more complex features that are expected to be found in mature clients (e.g. HATEOS support, metrics, Swagger support, authentication, etc).

Usage

Resources package

The generic REST API client library.

  1. In order to call an API you need to first instantiate a resource with NewResource()

    res := resources.NewResource("http://localhost:8080/v1/membership/users")
    

    Specify the API endpoint corresponding to this resource as a parameter. By default, you can read and write JSON requests and responses.

    You can also use the URL as a template with named parameters enclosed within curly braces and that will be resolved later on with Request() (see below.)

    res := resources.NewResource("http://localhost:8080/v1/membership/users/{user_id}")
    

    You can change the behaviour of this resource with chainable methods:

    • WithMarshaller() lets you change the default request and response serializer/deserializer by specifying a new marshaller midlleware. Right now only a JSON-specific (de)serializer is implemented.

      res.WithMarshaller(serializers.NewJsonMarshaller())
      
    • WithClient() lets you override the default HTTP client engine if needed.

      res.WithClient(http.DefaultClient)
      
    • WithTimeout() lets you define a custom request timeout, in seconds, that globally applies to all verbs on this resource. By default it is set to 30s.

      res.WithTimeout(60)
      
    • WithRetrier() lets you select an alternative call retry strategy by specifying a new retrier middleware. Right now only an exponential backoff is implemented.

      res.WithRetrier(retriers.NewExponentialRetrier())
      

      The default exponential backoff retrying middleware will actually try to call the API again in case it captures a client timeout and the HTTP error codes 429, 500, 503, and 504. Each retry might not be triggered perfectly on time and deviate a bit from their planned scheduled (jittering). In any case, it will then stop retrying after 3 attempts.

      You can change the default behaviour of exponentialRetrier with the following chainable methods: WithRetryableCodes(), WithJitter(), WithMaxTries().

  2. On this resource you can then define a set of actions that corresponds to a specific combination of an HTTP verb and inputs. An action is setup using the Request() method.

    call, cancel, err := res.Request("GET", &map[string]string{
    	"user_id": id,
    }, nil)
    
    call, cancel, err := res.Request("POST", nil, save)
    

    The first parameter is the case-insensitive HTTP verb to use for this request. The second one is an optional map of string keys and values representing the named parameters and their corresponding values to replace in the template URL. The third parameter is the optional struct body to send as well, if needed.

    It returns a CallFunc and a CancelFunc (see below), and potential errors.

  3. The CallFunc function will let you make the actual HTTP request, that can be programmatically cancelled by executing the corresponding CancelFunc function. You can execute CallFunc multiple times in a row, or in parallel.

    body, code, err := call()
    
    go func() {
    	body, code, err := call()
        ...
    }()
    ...
    cancel()
    

    CallFunc returns the structured body of the response if available, as a map[string]interface{}, the HTTP status code, and potential errors.

Example of use

As a test implementation for this library, there's an example package example_user that provides standard Create, Fetch, and Delete operations on an imaginary user resource. In order to keep it simple I didn't expose the cancel function in this version.

Create

Create an user resource

body, status, err := sample_membership.Create("http://sampleapi:8080/", &user)

Set the protocol and host of the API and a example_user.Data struct that represents the user to persist. Gets back a example_user.Data struct corresponding to the response, the HTTP status, and potential errors.

Fetch

Retch a specific user resource

body, status, err := example_user.Fetch("http://sampleapi:8080", userId)

Set the protocol and host of the API and the user identifier of the resource you want to read. Gets back a example_user.Data struct corresponding to theresponse, the HTTP status, and potential errors.

Delete

Delete a specific user resource

body, status, err := example_user.Delete("http://sampleapi:8080/", userId, version)

Set the protocol and host of the API and the user identifier and version of the resource you want to remove. Gets back a example_user.Data struct corresponding to the response, the HTTP status, and potential errors.

Owner
okay_awright
okay_awright
iceportal-api is a Golang client implementation to interact with the REST API of iceportal.de when connected to the WiFi-Network offered in German ICE Trains.

iceportal-api is a Golang client implementation to interact with the REST API of iceportal.de when connected to the WiFi-Network offered in German ICE Trains.

Fabian Siegel 42 Aug 3, 2022
Sample program of GCP pub/sub client with REST API

GCP pub/sub sample using REST API in Go GCP pub/sub publisher and subscriber sample programs. These use REST API and don't use pub/sub client library

Shohei YOSHIDA 0 Oct 12, 2021
Mortar is a GO framework/library for building gRPC (and REST) web services.

Mortar Mortar is a GO framework/library for building gRPC (and REST) web services. Mortar has out-of-the-box support for configuration, application me

null 624 Aug 3, 2022
simple golang rest service

Simplesrv simple golang rest service Local deployment (temp) Create k3d cluster with local registry and port configuraiton k3d create --enable-registr

Michael Filanov 0 Oct 24, 2021
Simple mDNS client/server library in Golang

mdns Simple mDNS client/server library in Golang. mDNS or Multicast DNS can be used to discover services on the local network without the use of an au

HashiCorp 894 Jul 30, 2022
Prisma Client Go is an auto-generated and fully type-safe database client

Prisma Client Go Typesafe database access for Go Quickstart • Website • Docs • API reference • Blog • Slack • Twitter Prisma Client Go is an auto-gene

Prisma 1.3k Aug 2, 2022
The Dual-Stack Dynamic DNS client, the world's first dynamic DNS client built for IPv6.

dsddns DsDDNS is the Dual-Stack Dynamic DNS client. A dynamic DNS client keeps your DNS records in sync with the IP addresses associated with your hom

Ryan Young 11 Jul 8, 2022
Go Substrate RPC Client (GSRPC)Go Substrate RPC Client (GSRPC)

Go Substrate RPC Client (GSRPC) Substrate RPC client in Go. It provides APIs and types around Polkadot and any Substrate-based chain RPC calls. This c

Chino Chang 1 Nov 11, 2021
Server and client implementation of the grpc go libraries to perform unary, client streaming, server streaming and full duplex RPCs from gRPC go introduction

Description This is an implementation of a gRPC client and server that provides route guidance from gRPC Basics: Go tutorial. It demonstrates how to u

Joram Wambugu 0 Nov 24, 2021
Godaddy-domains-client-go - Godaddy domains api Client golang - Write automaticly from swagger codegen

Go API client for swagger Overview This API client was generated by the swagger-codegen project. By using the swagger-spec from a remote server, you c

Mickael Stanislas 0 Jan 9, 2022
Tailscale-client-go - A client implementation for the Tailscale HTTP API

tailscale-client-go A client implementation for the Tailscale HTTP API Example p

David Bond 10 Jun 29, 2022
Comunicación de envios de archivos entres cliente-servidor, client-client.

Client - Server - Client Estes es un proyecto simple de comunicacion de envios de archivos del cliente al servidor y viceversamente, y de cliente a cl

Melvin RB 1 Jul 16, 2022
A Realtime API Gateway used with NATS to build REST, real time, and RPC APIs, where all your clients are synchronized seamlessly.

Realtime API Gateway Synchronize Your Clients Visit Resgate.io for guides, live demos, and resources. Resgate is a Go project implementing a realtime

Resgate.io - Synchronize Your Clients 585 Aug 1, 2022
gRPC/REST proxy for Kafka

Kafka-Pixy (gRPC/REST Proxy for Kafka) Kafka-Pixy is a dual API (gRPC and REST) proxy for Kafka with automatic consumer group control. It is designed

Mailgun Team 696 Aug 1, 2022
Control your legacy Reciva based internet radios (Crane, Grace Digital, Tangent, etc.) via REST api or web browser.

reciva-web-remote Control your legacy Reciva based internet radios (Crane, Grace Digital, Tangent, etc.) via REST api or web browser. Usage This progr

null 6 May 3, 2022
The rest api that can manage the iptables rules of the remote host

fiewall-api firewall api是基于firewalld来远程管理iptables规则的rest-api,无需部署agent Features 指定一个主机ip,让这个主机上的iptables增加一个规则 处理单个IP或CIDR范围(xx.xx.xx.xx/mask,mac,inte

seal 0 Mar 24, 2022
Transparent TLS and HTTP proxy serve and operate on all 65535 ports, with domain regex whitelist and rest api control

goshkan Transparent TLS and HTTP proxy serve & operating on all 65535 ports, with domain regex whitelist and rest api control tls and http on same por

Sina Ghaderi 10 Aug 2, 2022
Bridge between mattermost, IRC, gitter, xmpp, slack, discord, telegram, rocketchat, twitch, ssh-chat, zulip, whatsapp, keybase, matrix, microsoft teams, nextcloud, mumble, vk and more with REST API

bridge between mattermost, IRC, gitter, xmpp, slack, discord, telegram, rocketchat, twitch, ssh-chat, zulip, whatsapp, keybase, matrix, microsoft teams, nextcloud, mumble, vk and more with REST API (mattermost not required!)

Wim 5.1k Aug 9, 2022