Skip to content

gbrlsnchs/rest

Repository files navigation

rest (RESTful HTTP handler for Go)

Build Status Sourcegraph GoDoc Minimal Version

About

This package implements a simple RESTful HTTP handler that facilitates receiving requests or sending responses in JSON or XML by using a custom context.

Usage

Full documentation here.

Installing

Go 1.10

vgo get -u github.com/gbrlsnchs/rest

Go 1.11 or after

go get -u github.com/gbrlsnchs/rest

Importing

import (
	// ...

	"github.com/gbrlsnchs/rest"
)

Setting a wrapper

Consider the following type to be received / sent

type message struct {
	content string `json:"content,omitempty"`
}

Now, set the main handler

http.Handle("/", &rest.Wrapper{
	Handler: rest.HandlerFunc(func(ctx *rest.Context) {
		var ping message
		if err := ctx.ReceiveJSON(&ping); err != nil {
			// handle error
		}
		if ping.content != "ping" {
			ctx.Send(http.StatusBadRequest)
			return
		}
		pong := message{"pong"}
		ctx.SendJSON(pong, http.StatusOK)
	}),
	RecoverHandler: rest.HandlerFunc(func(ctx *rest.Context) {
		ctx.Send(http.StatusInternalServerError)
	}),
})

Contributing

How to help