rest

package module
v0.0.0-...-036eace Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 18, 2020 License: GPL-3.0 Imports: 26 Imported by: 0

README

REST

Go library to create your own REST services easily

Examples

Simple Server

There are some examples into the folder with the same name. The most basic one is the simple server. You can find in under simple subfolder.

Update example dependencies with

$ go get -t ./examples/simple/...

and run it with:

$ go run ./examples/simple/server/main.go
Jan 26 20:41:31.880 I 01 example | Server unix socket started at /tmp/example_940156266/unix.socket
Jan 26 20:41:31.880 I 02 example | Server HTTPS started in port 8443

once it is up, you can reach its API by using any browser, curl or any other manner to call a REST API. IN this simple exapple you can create resources, list the existing ones, list or delete a specific one. Reources can include whatever value that you prefer.

Next are the available operations:

Method URL Description
POST /1.0/resources creates a new resource
GET /1.0/resources list all the available resources
GET /1.0/resource/[id] returns the details of a created resource
PUT /1.0/resource/[id] updates the value of the resource with [id] identifier
DELETE /1.0/resource/[id] deletes the [id] resource

You can request an operation using the available unix socket (look at the output traces when service starts up to know the exact path to the socket)

curl --unix-socket /tmp/example_940156266/unix.socket s/1.0/resources

or by requesting the HTTPS endpoint

curl -k https://localhost:8443/1.0/resources
Build docker container

You can deploy simple server in a docker container. There is a Makefile ready to build such container in just one step:

make

that would create a docker container for testing and building source code and a second definitive one taking the binary and starting it up in 8443 port. The result is an image tagged with simple-server:[TAG]. The tag value is an abbreviation of the last git commit.

You can run locally a container based on such image with:

docker run -p 8443:8443 simple-server

Now, the port 8443 is accessible in localhost to reach the API

Deploy to Kubernetes

A further step is deploy this simple server as a Kubernetes pod. In the root of the project you can find a deployment file named simple-server-deployment.yaml to accomplish this.

First of all, let's publish our image to a repository. For this example we use docker hub, but you can use any other.

Login to hub, tag the image and push.

docker login --username [username] --password [password]
docker tag [image-id] [username]/[repo]:[tag]
docker push [username]/[repo]

!!! Note: Replace the placeholders (username, password, image-id, repo, tag) by their value

Next, deploy to the cluster. You can use Minikube to test it locally. Asuming that it is installed, start it if needed

minikube start

Deploy:

kubectl create -f simple-server-deployment.yaml
kubectl get pods

!!! Note: Edit the file and replace the image path with the one created in the docker hub

Look for the exposed url

$ minikube service simple-server --url
https://192.168.39.200:32028

Now you know where is the endpoint where REST API is exposed:

curl -k https://1192.168.39.200:32028/1.0/resources

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NotImplemented     = &errorResponse{http.StatusNotImplemented, "not implemented"}
	NotFound           = &errorResponse{http.StatusNotFound, "not found"}
	Forbidden          = &errorResponse{http.StatusForbidden, "not authorized"}
	Conflict           = &errorResponse{http.StatusConflict, "already exists"}
	ServiceUnavailable = &errorResponse{http.StatusServiceUnavailable, "service unavailable"}
)

Different error responses

View Source
var EmptySyncResponse = &syncResponse{success: true, metadata: make(map[string]interface{})}

EmptySyncResponse returns an empty synchronous response

Functions

func IsRecursionRequest

func IsRecursionRequest(r *http.Request) bool

IsRecursionRequest checks whether the given HTTP request is marked with the "recursion" flag in its form values.

Types

type API

type API struct {
	Version    string
	Middleware MiddlewareFunc
	Commands   []*Command
}

API holds all the commands and metadata for a specific version of the API

type Command

type Command struct {
	Name       string
	Middleware MiddlewareFunc

	GET    handlerFunc
	PUT    handlerFunc
	POST   handlerFunc
	DELETE handlerFunc
	PATCH  handlerFunc
}

Command is the basic structure for every API call.

type FileResponseEntry

type FileResponseEntry struct {
	Identifier string
	Path       string
	Filename   string
	Buffer     []byte /* either a path or a buffer must be provided */
}

FileResponseEntry is a file transfer response

type MiddlewareFunc

type MiddlewareFunc func(inner http.Handler) http.Handler

MiddlewareFunc describes a function uses to process a HTTP request as a middleman

type Operation

type Operation struct {
	// contains filtered or unexported fields
}

Operation struct holding metadata for an API operation, including handlers for run, cancel or socket connection; metadata, status or dates it was created, updated, etc..

func (*Operation) Cancel

func (op *Operation) Cancel() error

Cancel calls internal context cancel() method

func (*Operation) Render

func (op *Operation) Render() (string, *api.Operation, error)

Render writes in response the operation details, included the list of resources (urls)

func (*Operation) Run

func (op *Operation) Run() error

Run executes internal 'onRun' provided handler

func (*Operation) WaitFinal

func (op *Operation) WaitFinal(timeout int) error

WaitFinal waits for the operation to be completed

type Request

type Request struct {
	HTTPRequest *http.Request
	// contains filtered or unexported fields
}

Request represents the context of a REST request

func (*Request) CreateOperation

func (r *Request) CreateOperation(
	description string,
	opResources map[string][]string,
	opMetadata interface{},
	onRun func(*Operation) error,
	cancel context.CancelFunc) (*Operation, error)

CreateOperation creates an operation to be executed asynchronously

func (*Request) IsRecursionRequest

func (r *Request) IsRecursionRequest() bool

IsRecursionRequest checks whether the given HTTP request is marked with the "recursion" flag in its form values.

type Response

type Response interface {
	Render(w http.ResponseWriter) error
	String() string
}

Response knows how to render itself

func AuthorizationError

func AuthorizationError(err error) Response

AuthorizationError returns a 401 http response renderer

func BadRequest

func BadRequest(err error) Response

BadRequest returns a 400 http response renderer

func FileResponse

func FileResponse(r *http.Request, files []FileResponseEntry, headers map[string]string, removeAfterServe bool) Response

FileResponse returns a response renderer for a file download

func ForwardedResponse

func ForwardedResponse(doer client.Doer, request *http.Request, path string) Response

ForwardedResponse forwards a request to another endpoint and propagates back the response

func InternalError

func InternalError(err error) Response

InternalError returns a 500 http response renderer

func NotFoundError

func NotFoundError(what string) Response

NotFoundError returns a 404 http response renderer

func OperationResponse

func OperationResponse(op *Operation) Response

OperationResponse returns an http response renderer for an operation request

func PreconditionFailed

func PreconditionFailed(err error) Response

PreconditionFailed returns a 412 http response renderer

func SmartError

func SmartError(err error) Response

SmartError returns the right error message based on err.

func SyncResponse

func SyncResponse(success bool, metadata interface{}) Response

SyncResponse returns a synchronous http response renderer

func SyncResponseETag

func SyncResponseETag(success bool, metadata interface{}, etag interface{}) Response

SyncResponseETag returns a synchronous http response renderer with a etag header value

func SyncResponseHeaders

func SyncResponseHeaders(success bool, metadata interface{}, headers map[string]string) Response

SyncResponseHeaders returns a synchronous response with custom headers

func SyncResponseLocation

func SyncResponseLocation(success bool, metadata interface{}, location string) Response

SyncResponseLocation returns a synchronous http response renderer with a location header

func SyncResponseRedirect

func SyncResponseRedirect(address string) Response

SyncResponseRedirect returns a 3xx permanent redirect response

type Service

type Service struct {
	UnixSocketPath string
	// Group to own the unix socket created to expose REST locally
	UnixSocketOwner string
	ServerCertPath  string
	ServerKeyPath   string
	CAPath          string

	Router *mux.Router
	// Host where server listens. If empty, server listens in all host IPs
	Host string
	// Service port
	Port int

	// Dispatcher of jobs/workers to attend asynchronous requests
	MaxQueuedOperations     int
	MaxConcurrentOperations int
	// contains filtered or unexported fields
}

A Service can respond to http requests to the REST API

func (*Service) Init

func (d *Service) Init(apis []*API)

Init initializes REST service daemon by creating mux router if not created, populate router with defined array of APIs, open and setup database

func (*Service) Shutdown

func (d *Service) Shutdown() error

Shutdown additional tasks when service shutdown

func (*Service) Start

func (d *Service) Start() error

Start starts the daemon on the configure endpoint

Directories

Path Synopsis
cli
Package endpoints is a generated GoMock package.
Package endpoints is a generated GoMock package.
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL