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)
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"
}
}