• Stars
    star
    149
  • Rank 248,619 (Top 5 %)
  • Language
    Go
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An extremely simple to use, lightweight, yet powerful REST Client

Restful

A Rest Client for Go (Golang)

========

An extremely simple to use, lightweight, yet powerful REST Client

Motivation

The Go http standard library is a great library, but it might sometimes be a bit too low level to use, and it doesn't offer features like fork-join requests for better performance, response caching based on headers, and the possibility to mockup responses.

Features and Roadmap

v0.1

  • GET, POST, PUT, PATCH, DELETE, HEAD & OPTIONS HTTP verbs
  • Dead simple, synchronous requests
  • Automatic caching of hosts connections
  • Response Caching, based on response headers (cache-control, last-modified, etag, expires)
  • Local caching strategies: TTL, LRU & Max Byte Size.
  • Mockups!
  • Fork-Join request pattern, for sending many requests concurrently, improving client perfomance.
  • Async request pattern.
  • Request Body can be string, []byte, struct & map.
  • Automatic marshal and unmarshal for JSON and XML Content-Type. Default JSON.
  • Full access to http.Response object.
  • Retries
  • BasicAuth
  • UserAgent
  • Gzip support
  • HTTP/2 support (automatic with Go +1.6)

v0.2

v0.3

  • Custom Root Certificates and Client Certificates
  • Testing +95%

v0.4

  • Plugable external caches like Memcached

Caching

Caching is done by two strategies working together: Time To Live (TTL) and Least Recently Used (LRU). Objects are inserted in the cache based on Response Headers. You can establish a maximum Memory Size for the cache and objects are flushed based on time expiration (TTL) or by hitting the maximum memory limit. In the last case, least accessed objects will be removed first.

Examples

Installation

clone en tu gopath o goroot

git clone https://github.com/mercadolibre/golang-restclient/

Importing

import "github.com/mercadolibre/golang-restclient/rest"

Simple GET

resp := rest.Get("https://api.restfulsite.com/resource")

Simple POST

// Using a `string` as body
resp := rest.Post("https://api.restfulsite.com/resource", "Body")

Simple POST, with Struct Body

type User struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

body := new(User)
body.Id = 1
body.Name = "Hernan"

// body will be marshall as JSON
resp := rest.Post("https://api.restfulsite.com/resource/1", body)
fmt.Println(resp)

Fork Join

ForkJoin let you fork requests, and wait until all of them have return.

Concurrent has methods for Get, Post, Put, Patch, Delete, Head & Options, with the almost the same API as the synchronous methods. The difference is that these methods return a FutureResponse, which holds a pointer to Response. Response inside FutureResponse is nil until request has finished.

var f [3]*rest.FutureResponse

// ForkJoin will send all requests concurrently
// and will wait until all requests have their correspondent responses
rest.ForkJoin(func(c *rest.Concurrent) {
	f[0] = c.Get("https://api.restfulsite.com/resource/1")
	f[1] = c.Get("https://api.restfulsite.com/resource/2")
	f[2] = c.Get("https://api.restfulsite.com/resource/3")
})

for i := range f {
  if f[i].Response().StatusCode == http.StatusOK {
    fmt.Println(f[i].Response())
  }
}

Async

Async let you make Restful requests in an asynchronous way, without blocking the go routine calling the Async function.

Whenever the Response is ready, the f function will be called back.

// This won't be blocked.
rest.AsyncGet("https://api.restfulsite.com/user", func(r *rest.Response) {
	if r.StatusCode == http.StatusOK {
		fmt.Println(r)
	}
})

// This will be printed first.
fmt.Println("print first")

Defaults

  • Headers: keep-alive, Cache-Control: no-cache
  • Timeout: 2 seconds
  • ContentType: JSON (for body requests in POST, PUT and PATCH)
  • Cache: enable
  • Cache Size: 1GB
  • Idle Connections Per Host: 2 (the default of http.net package)
  • HTTP/2: automatic with Go 1.6
  • Gzip: automatic support for gzip responses

RequestBuilder

RequestBuilder gives you the power to go beyond defaults. It is possible to set up headers, timeout, baseURL, proxy, contentType, not to use cache, directly disabling timeout (in an explicit way), and setting max idle connections.

// You can reuse in every RequestBuilder
customPool := &rest.CustomPool{
	MaxIdleConnsPerHost: 100,
}

headers := make(http.Header)
headers.Add("myHeader", "myValue")

var rb = rest.RequestBuilder{
	Headers:             headers,
	Timeout:             200 * time.Millisecond,
	BaseURL:             "https://baseURL",
	Proxy:               "http://myproxy",
	ContentType:         rest.JSON,
	DisableCache:        false,
	DisableTimeout:      false,
	MaxIdleConnsPerHost: 10,
	CustomPool:     customPool,
}

resp := rb.Get("/mypath")

Mockups

When using mockups all requests will be sent to the mockup server. To activate the mockup environment you have two ways: using the flag -mock

go test -mock

Or by programmatically starting the mockup server

StartMockupServer()

A mockup example

myURL := "http://mytest.com/foo"

myHeaders := make(http.Header)
myHeaders.Add("Hello", "world")

mock := rest.Mock{
	URL:          myURL,
	HTTPMethod:   http.MethodGet,
	ReqHeaders:   myHeaders,
	RespHTTPCode: http.StatusOK,
	RespBody:     "foo",
}

rest.AddMockups(&mock)

v := rest.Get(myURL)

More Repositories

1

chico

A collection of easy-to-use UI components.
JavaScript
343
star
2

php-sdk

MercadoLibre's PHP SDK
PHP
184
star
3

python-sdk

MercadoLibre's Python SDK
Python
131
star
4

net-sdk

MercadoLibre's .NET SDK
C#
56
star
5

mercadolibre.js

MercadoLibre API Client
49
star
6

java-sdk

MercadoLibre's Java SDK
Java
46
star
7

java-restclient

A lightweight REST client implementation for Java 1.7+.
Java
37
star
8

cacique

mercadolibre's Cacique is a automation test tool distribuited under gpl licence. BETA Version
JavaScript
32
star
9

fury-core-ci

Github actions for Fury Core applications
TypeScript
31
star
10

flamepool

Go
29
star
11

polp-fiction-metrics

polp-fiction-metrics
Python
28
star
12

ruby-sdk

MercadoLibre's Ruby SDK
Ruby
25
star
13

golang-sdk

MercadoLibre's Golang SDK
Go
24
star
14

mobile-dependencies_whitelist

Whitelist dependencies files for mobile teams
Ruby
23
star
15

meli-card-drawer-ios

Meli Card Drawer iOS - Shared credit card UI component
Swift
22
star
16

meli-card-drawer-android

Meli Card Drawer Android - Shared credit card UI component
Kotlin
19
star
17

nodejs-sdk

JavaScript
18
star
18

MPTopFloatingView

Objective-C
17
star
19

toiler

Toiler is a AWS SQS long-polling thread-based message processor.
Ruby
16
star
20

ubatch

uBatch is a simple, yet elegant library for processing streams data in micro batches.
Python
15
star
21

tiny.js

A JavaScript utility library oriented to real world tasks
JavaScript
13
star
22

workshop-docker-fullstack2017

workshop-docker-fullstack2017
CSS
11
star
23

piper

A minimal pipeline library for golang
Go
10
star
24

MPDynamicSkeleton

Modularized skeleton with gradient animation
Swift
10
star
25

assimilator

A Restful JSON API that controls policies and routes from different firewall brands.
Python
9
star
26

cx-frontend-challenge

JavaScript
9
star
27

payment-methods-component

CSS
9
star
28

workshop-docker

Meli Docker Workshop
JavaScript
8
star
29

arcanist-extensions

PHP
8
star
30

resilience-workshop-api

Java
8
star
31

mlbusiness-components-ios

Shared Business UI components
Swift
7
star
32

java-circuit-breaker

Circuit breaker for Java 1.7+.
Java
7
star
33

fury_mobile-ios-ui

Objective-C
6
star
34

seamless-iframe

A fallback that emulates the main features of the seamless iframe.
JavaScript
6
star
35

flexbuffer-node

Node based library that gives you a variety of options for buffer optimization.
JavaScript
6
star
36

card-form-android

Kotlin
5
star
37

srt

Python
5
star
38

workshop_python_brasil_2021

HTML
4
star
39

fury-little_monster-gem

Ruby
4
star
40

card-form-ios

Swift
4
star
41

HadoopCryptoCompressor

Crypto compressor for hdfs that enable to compress with public key any file into hdfs
Java
4
star
42

java-metrics

This interface helps you to collect, measure and record metrics in Java applications
Java
4
star
43

java-json

A Json interface for Java applications
Java
3
star
44

java-sdk-repo

MercadoLibre's Java SDK Maven Repository
2
star
45

MLDynamicModal

Custom modal for iOS with swipe, tap and button dismiss recognizer
Objective-C
2
star
46

productidentifiers-frontend-demo

CSS
2
star
47

mlbusiness-components-android

Java
2
star
48

grails-esi

An ESI plugin for grails
Groovy
2
star
49

point-mainapp-demo-android

Kotlin
1
star
50

fury_device-sdk-ios

Swift
1
star
51

presentacion-plataformas-lenguajes-web

JavaScript
1
star
52

curso_ios_lp

curso ios - ejercicios
Objective-C
1
star