• Stars
    star
    166
  • Rank 227,748 (Top 5 %)
  • Language
    Erlang
  • License
    Apache License 2.0
  • Created over 10 years ago
  • Updated about 2 months ago

Reviews

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

Repository Details

For the times you need more than just a gun.

shotgun

For the times you need more than just a gun.

Rationale

After using the gun library on a project where we needed to consume Server-sent Events (SSE) we found that it provided great flexibility, at the cost of having to handle each raw message and data, including the construction of the response body data. Although this is great for a lot of scenarios, it can get cumbersome and repetitive after implementing it a couple of times. This is why we ended up creating shotgun, an HTTP client that uses gun behind the curtains but provides a simple API that has out-of-the-box support for SSE.

Usage

shotgun uses maps and hence requires Erlang 17 to compile and run.

shotgun is an OTP application, so before being able to use it, it has to be started. Either add it as one of the applications in your .app file or run the following code:

application:ensure_all_started(shotgun).

Regular Requests

Once the application is started a connection needs to be created in order to start making requests:

{ok, Conn} = shotgun:open("google.com", 80),
{ok, Response} = shotgun:get(Conn, "/"),
io:format("~p~n", [Response]),
shotgun:close(Conn).

Which results in:

#{body => <<"<HTML><HEAD>"...>>,
  headers => [
     {<<"location">>,<<"http://www.google.com/adfs">>},
     {<<"content-type">>,<<"text/html; charset=UTF-8">>},
     {<<"x-content-type-options">>,<<"nosniff">>},
     {<<"date">>,<<"Fri, 17 Oct 2014 17:18:32 GMT">>},
     {<<"expires">>,<<"Sun, 16 Nov 2014 17:18:32 GMT">>},
     {<<"cache-control">>,<<"public, max-age=2592000">>},
     {<<"server">>,<<"sffe">>},
     {<<"content-length">>,<<"223">>},
     {<<"x-xss-protection">>,<<"1; mode=block">>},
     {<<"alternate-protocol">>,<<"80:quic,p=0.01">>}
   ],
   status_code => 302}
}

%= ok

Immediately after opening a connection we did a GET request, where we didn't specify any headers or options. Every HTTP method has its own shotgun function that takes a connection, a uri (which needs to include the slash), a headers map or a proplist containing the headers, and an options map. Some of the functions (post/5, put/5 and patch/5) also take a body argument.

Alternatively there's a generic request/6 function in which the user can specify the HTTP method as an argument in the form of an atom: get, head, options, delete, post, put or patch.

IMPORTANT: When you are done using the shotgun connection remember to close it with shotgun:close/1.

HTTP Secure Requests

It is possible to tell shotgun to use SSL by providing the atom https as the third argument when creating a connection with to the open function. Just like when performing HTTP requests it is also necessary to specify a port. HTTPS servers typically listen for connections on port 443 and this will be the most likely value you'll need to use.

Basic Authentication

If you need to provide basic authentication credentials in your requests, it is as easy as specifying a basic_auth entry in the headers map:

{ok, Conn} = shotgun:open("site.com", 80),
{ok, Response} = shotgun:get(Conn, "/user", #{basic_auth => {"user", "password"}}),
, or
{ok, Response} = shotgun:get(Conn, "/user", [{basic_auth, {"user", "password"}}]),
shotgun:close(Conn).

Specifying a Timeout

The timeout option can be used to specify a value for all types of requests:

{ok, Conn} = shotgun:open("google.com", 80).
{error, Error} = shotgun:get(Conn, "/", #{}, #{timeout => 10}).
io:format("~p~n", [Error]).
%%= {timeout,{gen_fsm,sync_send_event,[<0.368.0>,{get,{"/",[],[]}},10]}}
shotgun:close(Conn).

The default timeout value is 5000 if none is specified.

Consuming Server-sent Events

To use shotgun with endpoints that generate SSE the request must be configured using some values in the options map, which supports the following entries:

  • async ::boolean(): specifies if the request performed will return a chunked response. It currently only works for GET requests.. Default value is false.

  • async_mode :: binary | sse: when async is true the mode specifies how the data received will be processed. binary mode treats each chunk received as raw binary. sse mode buffers each chunk, splitting the data received into SSE. Default value is binary.

  • handle_event :: fun((fin | nofin, reference(), binary()) -> any()): this function will be called each time either a chunk is received (async_mode = binary) or an event is parsed (async_mode = sse). If no handle_event function is provided the data received is added to a queue, whose values can be obtained calling the shotgun:events/1. Default value is undefined.

The following is an example of the usage of shotgun when consuming SSE.

{ok, Conn} = shotgun:open("localhost", 8080).
%= {ok,<0.6003.0>}

Options = #{async => true, async_mode => sse},
{ok, Ref} = shotgun:get(Conn, "/events", #{}, Options).
%= {ok,#Ref<0.0.1.186238>}

% Some event are generated on the server...
Events = shotgun:events(Conn).
%= [{nofin, #Ref<0.0.1.186238>, <<"data: pong">>}, {nofin, #Ref<0.0.1.186238>, <<"data: pong">>}]

shotgun:events(Conn).
%= []

Notice how the second call to shotgun:events/1 returns an empty list. This is because events are stored in a queue and each call to events returns all events queued so far and then removes these from the queue. So it's important to understand that shotgun:events/1 is a function with side-effects when using it.

Additionally shotgun provides a parse_event/1 helper function that turns a server-sent event binary into a map:

shotgun:parse_event(<<"data: pong\ndata: ping\nid: 1\nevent: pinging">>).
%= #{data => [<<"pong">>,<<"ping">>],event => <<"pinging">>,id => <<"1">>}

Building & Test-Driving

To build shotgun just run the following on your command shell:

rebar3 compile

To start up a shell where you can try things out run the following (after building the project as described above):

rebar3 shell

Contact Us

If you find any bugs or have a problem while using this library, please open an issue in this repo (or a pull request :)).

And you can check all of our open-source projects at inaka.github.io

More Repositories

1

erlang_guidelines

Inaka's Erlang Coding Guidelines
Erlang
619
star
2

EventSource

A simple Swift client library for the Server Sent Events (SSE)
Swift
483
star
3

galgo

When you want your logs to be displayed on screen
Java
427
star
4

elvis

Erlang Style Reviewer
Erlang
424
star
5

apns4erl

Apple Push Notification Server for Erlang
Erlang
369
star
6

TinyTask

A Tiny Task Library
Java
324
star
7

worker_pool

Erlang worker pool
Erlang
274
star
8

sumo_db

Erlang Persistency Framework
Erlang
173
star
9

Dayron

A repository `similar` to Ecto.Repo that maps to an underlying http client, sending requests to an external rest api instead of a database
Elixir
159
star
10

cowboy_swagger

Swagger integration for Cowboy (built on trails)
Erlang
120
star
11

gold_fever

A Treasure Hunt for Erlangers
Erlang
86
star
12

Jayme

Abstraction layer that eases RESTful interconnections in Swift
Swift
81
star
13

guidelines

General Inaka Guidelines
75
star
14

cowboy-trails

A couple of improvements over Cowboy Routes
Erlang
71
star
15

jem.js

Just Erlang Maps for Javascript
JavaScript
69
star
16

sheldon

Very Simple Erlang Spell Checker
Erlang
62
star
17

elvis_core

The core of an Erlang linter
Erlang
61
star
18

niffy

Inline C code in Erlang modules to build NIFs
Erlang
60
star
19

sumo_rest

Generic cowboy handlers to work with Sumo
Erlang
59
star
20

serpents

Multi-Player Game on top of HDP protocol
Erlang
56
star
21

xref_runner

Erlang Xref Runner (inspired in rebar xref)
Erlang
50
star
22

erlang-github

Github API client
Erlang
46
star
23

lasse

SSE handler for Cowboy
Erlang
45
star
24

beam_olympics

Let's find the fastest beamer!
Erlang
39
star
25

fiar

Four in a Row - A game to learn Erlang
Erlang
36
star
26

zipper

Generic Zipper implementation in Erlang
Erlang
34
star
27

ios-xmpp-sample

Blog post sample project.
Swift
33
star
28

kotlillon

Android Kotlin Examples
Kotlin
33
star
29

katana-test

Meta Testing Utilities for common_test
Erlang
32
star
30

match_stream

A sample project to show in our scale blog post
JavaScript
30
star
31

phoenix_passwordless_login

Phoenix Passwordless Login
Elixir
29
star
32

KillerTask

Android AsyncTask wrapper library, written in Kotlin
Kotlin
26
star
33

canillita

Simple Paperboy-themed PubSub
Erlang
26
star
34

lewis

Rock your Android
Java
22
star
35

tirerl

Erlang interface to Elastic Search
Erlang
19
star
36

itweet

Twitter Stream API on ibrowse
Erlang
18
star
37

katana-code

Code Utilities for Erlang
Erlang
17
star
38

pusherman

queuing system for push notifications
Erlang
17
star
39

galgo-ios

When you want your logs to be displayed on screen
Objective-C
16
star
40

lsl

NIM in Erlang
Erlang
15
star
41

credo_server

Credo Server
Elixir
15
star
42

FadeButton

Fading effects for UIButtons made simple
Swift
15
star
43

Jolly

Jolly Chimp that keeps track of our Github Repos
Swift
12
star
44

rpsls

Rock Paper Scissors Lizzard Spock World Championship in Erlang
Erlang
12
star
45

ikbot

An elixir based customizable hipchat bot
Elixir
12
star
46

nconf

Nested Configuration Manager for Erlang Applications
Erlang
12
star
47

pushito

APNS over HTTP/2
Elixir
11
star
48

rest_guidelines

REST API Design Guidelines
11
star
49

fetjaba

From Erlang To Java and Back Again
Erlang
9
star
50

sumo_db_pgsql

PostgreSQL adapter for sumo_db.
Erlang
9
star
51

jinterface_stdlib

Erlang stdlib implementation on Java, based on JInterface
Java
9
star
52

IKCapture

Snapchat-Like Image Capture Library
Objective-C
8
star
53

MediaPickerController

Neat API for presenting the classical action sheet for picking an image or video from the device or camera.
Swift
8
star
54

PictureViewMaster

Interactive image projector.
Swift
8
star
55

toy_kv

A simple and reduced Key-Value Store written in Erlang
Erlang
7
star
56

ColorPicker

Color Picker for Swift
Swift
7
star
57

swift_guidelines

Inaka's Swift Coding Guidelines
7
star
58

spellingci

Spelling CI Server
Erlang
7
star
59

talks

Sources and pdfs of our talks and speeches
TeX
6
star
60

bookmarks

A collection of bookmarks for Inakos
6
star
61

IKJayma

RESTful API abstraction for Server Interconnection
Objective-C
6
star
62

hexer

Hex.pm integration in escript format.
Erlang
6
star
63

hexer.mk

erlang.mk plugin for hexer
Makefile
5
star
64

android_guidelines

Inaka's Android Development Guidelines
5
star
65

elvis.mk

3rd party erlang.mk plug-in for Elvis
Shell
5
star
66

plixir

Poker + Elixir + Phoenix
CSS
5
star
67

ios_guidelines

Inaka's iOS Coding Guidelines
Objective-C
4
star
68

sumo_db_elasticsearch

ElasticSearch adapter for sumo_db
Erlang
4
star
69

tele_sign

Node.js library to send messages through http://www.telesign.com/
JavaScript
4
star
70

inaka.github.io

Inaka's Open Source Projects
HTML
3
star
71

sumo_db_riak

Riak adapter for sumo_db
Erlang
3
star
72

android-excercises

Quick test for Android candidates
3
star
73

sumo_db_mongo

MongoDB adapter for sumo_db
Erlang
2
star
74

Otec

A swift app to showcase our best open-source libraries
Swift
2
star
75

gold_fever-solver

A solver for the http://github.com/inaka/gold_fever game
Erlang
2
star
76

inaka.mk

erlang.mk extras that we generally use in all of our projects
Makefile
2
star
77

g2x

Graffle to XCode
Objective-C
2
star
78

beam_olympics-extended

Internal repo to keep secret beam_olympics tasks from the public view
Erlang
2
star
79

beam_olympics-solver

Solutions for beam_olympics
Elixir
2
star
80

emarkdown

Based on https://github.com/devinus/markdown - but for Erlang :)
C
2
star
81

sumo_db_mysql

MySQL adapter for sumo_db
Erlang
2
star
82

ruby_guidelines

Our own guidelines when it comes to ruby development
1
star
83

pokedex

Dumb repo to prove what we can do with sumo{_db|rest_}
Erlang
1
star
84

homebrew-formulas

Homebrew formulas for some of our tools
Ruby
1
star
85

updike

Run, rabbit, run
1
star
86

ios-scripts

Helper scripts that you can use in your iOS apps
Shell
1
star
87

INSocketListener

SSE Socket Listener for Objective-C
Objective-C
1
star