Installation

Install the library into your GOPATH using:

    go get github.com/5Sigma/celerity

A simple API server

Instantiate a server

The core of celerity is the Server. Create a new server using the New function.

svr := celerity.New()

Build a route handler

This RouteHandler is a simple example for an endpoint that says hello to a name passed in the URL.

type HelloResponse struct {
  Message string `json:"message"`
}

func helloHandler (c celerity.Context) celerity.Response {
  name := c.URLParams.String("name")
  r := HelloResponse{ Message: fmt.Sprintf("Hello %s", name)  }
  return c.R(r) 
}

Define the route for the server

Define routing to link a route handler to a URL path. This route will use a URL variable to trap the a url such as /hello/john.

svr.GET("/hello/:name", helloHandler)

Routing can be broken up into groups called scopes and customized with middleware. The routing guide goes into more detail about how to setup more complex routing.

Start the server with preconfigured CLI handling

Celerity comes with the ability to roll out nice command line handling for the server; with configurable flags, configuration and environment reading and more. The HandleCLI function accepts a function which returns the server. This allows for some additional configuration when launching the server instance itself.

func main() {
  celerity.HandleCLI(func() *celerity.Server{
    svr := celerity.New()
    return svr
  })
}

Putting it all together

Here is the final code for our server:

import (
  "github.com/5Sigma/celerity"
)

type helloResponse struct {
  Message string `json:"message"`
}

func helloHandler (c celerity.Context) celerity.Response {
  name := c.URLParams.String("name")
  r := helloResponse{ Message: fmt.Sprintf("Hello %s", name)  }
  return c.R(r) 
}

func main() {
  celerity.HandleCLI(func() *celerity.Server {
    svr := celerity.New()
    svr.GET("/hello", helloHandler)
    return svr
  });
}

With this code we can now compile and run our server. Assuming your filename is main.go

go run main.go -- run

Once the server starts you can hit the endpoint you build at:

http://localhost:5000/hello/alice

With its default configuration you should get a JSON response back that resembles:

{
  "requestId":"AE74AB34C12FF4F1A34",
  "success": true,
  "meta": {},
  "data": {
    "message": "Hello alice"
  }
}

Routes command

You should also be able to see the route you created by checking the available routes using the routes command in your server binary. Run your server binary alone to for reference on the available commands.

last modified Thursday, June 21, 2018
Previous in Guides
Extracting Request Body Data
Extracting data out of the body of a request
Celerity is maintained by 5Sigma. Source code is available at Github.