rester

package module
v0.0.0-...-47b4a58 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2020 License: MIT Imports: 16 Imported by: 0

README

rester

Build Status GoDoc Go Report Card Coverage Status GitHub

An Opinionated library for building REST APIs in Go.

Simple rest resource with one method without checking the permissions


package main

import (
	"net/http"

	"github.com/hoenirvili/rester"
	"github.com/hoenirvili/rester/request"
	"github.com/hoenirvili/rester/resource"
	"github.com/hoenirvili/rester/response"
	"github.com/hoenirvili/rester/route"
)

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

type root struct{}

func (r *root) index(req request.Request) resource.Response {
	return response.Payload(&jsonResponse{"Hello World !"})
}

func (r *root) Routes() route.Routes {
	return route.Routes{{
		URL:     "/",
		Method:  resource.Get,
		Handler: r.index,
	}}
}

func main() {
	rester := rester.New()
	rester.Resource("/", new(root))
	rester.Build()
	if err := http.ListenAndServe(":8080", rester); err != nil {
		panic(err)
	}
}

Using the query api to query url parameters


package main

import (
	"fmt"
	"net/http"

	"github.com/hoenirvili/rester"
	"github.com/hoenirvili/rester/query"
	"github.com/hoenirvili/rester/request"
	"github.com/hoenirvili/rester/resource"
	"github.com/hoenirvili/rester/response"
	"github.com/hoenirvili/rester/route"
	"github.com/hoenirvili/rester/value"
)

type root struct {
}

type message struct {
	Str string `json:"message"`
}

func (r root) index(req request.Request) resource.Response {
	if err := req.Query("page").Error(); err != nil {
		return response.BadRequest("invalid page param")
	}

	page := req.Query("page").Int()
	str := fmt.Sprintf("get request with query param page=%d", page)
	return response.Payload(&message{str})
}

func (r root) Routes() route.Routes {
	return route.Routes{{
		URL:     "/",
		Method:  http.MethodGet,
		Handler: r.index,
		QueryPairs: query.Pairs{
			"page": query.Value{Type: value.Int},
		},
	}}
}
func main() {
	rester := rester.New()
	rester.Resource("/", new(root))
	rester.Build()
	if err := http.ListenAndServe(":8080", rester); err != nil {
		panic(err)
	}
}
For more examples how to use the API, please visit the examples folder.

Documentation

Overview

Package rester used to define and compose multiple HTTP REST resources The package offers abstractions in order to construct your REST API in a friendly and maintainable way, yet offering the flexibility for a well more complex solution

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(opt *Options)

Option defines a setter callback type to set an underlying option value

func WithCustomCors

func WithCustomCors(options cors.Options) Option

WithCustomCors set's a custom set of cors for the server

func WithTokenValidator

func WithTokenValidator(t TokenValidator) Option

WithTokenValidator sets the underlying token validation implementation to use to validate and extract token meta-data information to authorize and authenticate the

func WithVersioning

func WithVersioning(version string) Option

WithVersioning appends to the path route the prefix "/version/"

type Options

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

Options type holding all underlying options for the rester api

type Resource

type Resource interface {
	// Routes returns a list of sub-routes of the given resource
	Routes() route.Routes
}

Resource defines a way of composing routes into a resource

type Rester

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

Rester used for constructing and initializing the http router with routes

func New

func New(opts ...Option) *Rester

New returns a new Rester http.Handler compatible that's ready to serve incoming http rest request

func (*Rester) Build

func (r *Rester) Build()

Build builds the internal state of the router making it ready for dispatching requests

func (*Rester) MethodNotAllowed

func (r *Rester) MethodNotAllowed(h handler.Handler)

MethodNotAllowed defines a handler to respond whenever a method is not allowed on a route

func (*Rester) NotFound

func (r *Rester) NotFound(h handler.Handler)

NotFound defines a handler to respond whenever a route could not be found

func (*Rester) Resource

func (r *Rester) Resource(base string, resource Resource)

Resource initializes a resource with the all available sub-routes of the resource

func (*Rester) ServeHTTP

func (r *Rester) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP based on the incoming request route it to the available resource handler

func (*Rester) Static

func (r *Rester) Static(dir string)

Static serve static files from the location pointed by dir This has limited support so don't expect much customization

func (*Rester) StaticSpa

func (r *Rester) StaticSpa(dir string)

func (*Rester) UseGlobalMiddleware

func (r *Rester) UseGlobalMiddleware(m ...middleware)

UseGlobalMiddleware appends the list of middlewares into the global middleware stack to be put in front of every request emitted to the api

type TokenValidator

type TokenValidator interface {
	// Verify verifies if the request contains the desired token
	// This also can verify the expiration time or other claims
	// With success this will return the validated claims
	Verify(r *http.Request) (map[string]interface{}, error)
}

TokenValidator defines ways of interactions with the token

Directories

Path Synopsis
examples
jwt
Package handler used for defining custom handler types used by the internal HTTP router
Package handler used for defining custom handler types used by the internal HTTP router
Package permission holds types and functions used for defining the permission of resources
Package permission holds types and functions used for defining the permission of resources
Package query used for retrieving key, value pairs from a query URL adding a thin slice of utilities
Package query used for retrieving key, value pairs from a query URL adding a thin slice of utilities
Package resource defines types used for creating and decorating REST resources
Package resource defines types used for creating and decorating REST resources
Pakcage response used for creating custom HTTP responses
Pakcage response used for creating custom HTTP responses
Package token offers a basic jwt token validation method
Package token offers a basic jwt token validation method
Package value offers helper functions and types to parse value type strings
Package value offers helper functions and types to parse value type strings

Jump to

Keyboard shortcuts

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