Entradas etiquetadas como “go”

Using the great and simple Go http package is more than enough (and what I use) to expose simple HTTP endpoints. But when you need to build a HTTP API with lots of endpoints and user/media types, you have a lot of work ahead.

Design

First of all, we need to define the API using the goa DSL. Let’s create a dummy API to share secrets using One-Time links (OTL). It’s not the case of a complex API but it’s easy to show how to work with goa.

We will have 2 endpoints:

To store a new secret returning the corresponding OTL.

To retrieve a secret using its OTL.

To define the API create a package called design:

$ mkdir -p $GOPATH/src/github.com/julianvilas/dummy-secrets/design

And edit the file design.go (can be named as you want, e.g. api.go or split in different files).

By now we have added some basic information of the API. The BasePath will affect the URLs of all the resources we are going to add later, and the Scheme, Host and Consumes will affect both the client and the swagger documentation.

The client will contain a SDK, used by the cli, to interact with the API.

The app will implement all the needed low-level HTTP functions.

The swagger will contain the autogenerated documentation.

In the root directory, the main.go will start the HTTP server will all the API controllers (0 by now). That one, with the design package are the only we should modify. The others from above are auto-generated and shouldn’t be edited by hand.

Implement

First we need to create a storage where secrets can be stored and retrieved. In order to make things easy to test or replace and well organized, we will define a Persister interface. Let’s put it in its own package persister.

Run

Let’s test what we did. First of all, build and install again with go install ./....

Now use the cli to store a secret and the retrieve it:

$ dummy-secrets-cli
CLI client for the dummy-secrets service
Usage:
dummy-secrets-cli [command]
Available Commands:
create Store a new Secret
help Help about any command
show Get a Secret by its ID
Flags:
--dump Dump HTTP request and response.
-H, --host string API hostname (default "localhost:8080")
-s, --scheme string Set the requests scheme
-t, --timeout duration Set the request timeout (default 20s)
Use "dummy-secrets-cli [command] --help" for more information about a command.