rex

package module
v0.13.3 Latest Latest
Warning

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

Go to latest
Published: May 12, 2020 License: MIT Imports: 25 Imported by: 1

README

REX

REX provides a simple & light-weight REST server in Golang.

GoDoc

Example
package main

import (
    "github.com/ije/rex"
)

func main() {
    rex.Get("/:name", func(ctx *rex.Context) {
	    ctx.Ok("Hello, " + ctx.URL.Param("name"))
    })

    rex.Start(8080)
}

Documentation

Overview

Package rex provides a simple & light-weight REST server in golang

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Delete added in v0.9.0

func Delete(path string, handles ...Handle)

Delete is a shortcut for rest.Handle("DELETE", path, handles)

func Get added in v0.9.0

func Get(path string, handles ...Handle)

Get is a shortcut for rest.Handle("GET", path, handles)

func Head(path string, handles ...Handle)

Head is a shortcut for rest.Handle("HEAD", path, handles)

func NotFound added in v0.9.0

func NotFound(handle Handle)

NotFound sets a NotFound handle.

func Options added in v0.9.0

func Options(path string, handles ...Handle)

Options is a shortcut for rest.Handle("OPTIONS", path, handles)

func Patch added in v0.9.0

func Patch(path string, handles ...Handle)

Patch is a shortcut for rest.Handle("PATCH", path, handles)

func Post added in v0.9.0

func Post(path string, handles ...Handle)

Post is a shortcut for rest.Handle("POST", path, handles)

func Put added in v0.9.0

func Put(path string, handles ...Handle)

Put is a shortcut for rest.Handle("PUT", path, handles)

func Serve

func Serve(config ServerConfig)

Serve serves a rex server.

func Start added in v0.9.0

func Start(port uint16)

Start starts a REX server.

func StartAutoTLS added in v0.9.0

func StartAutoTLS(port uint16, hosts ...string)

StartAutoTLS starts a REX server with autocert powered by Let's Encrypto SSL

func StartTLS added in v0.9.0

func StartTLS(port uint16, certFile string, keyFile string)

StartTLS starts a REX server with TLS.

func Static added in v0.5.0

func Static(path string, root string, fallbackPath ...string)

Static handles static files requests.

func Trace added in v0.9.8

func Trace(path string, handles ...Handle)

Trace is a shortcut for rest.Handle("TRACE", path, handles)

func Use added in v0.9.0

func Use(middlewares ...Handle)

Use appends middleware to the REST middleware stack.

Types

type ACLUser added in v0.8.1

type ACLUser interface {
	Permissions() []string
}

A ACLUser contains the Permissions method that returns the acl permissions

type AutoTLSConfig added in v0.4.0

type AutoTLSConfig struct {
	AcceptTOS bool           `json:"acceptTOS"`
	Hosts     []string       `json:"hosts"`
	CacheDir  string         `json:"cacheDir"`
	Cache     autocert.Cache `json:"-"`
}

AutoTLSConfig contains options to support autocert by Let's Encrypto SSL.

type CORS

type CORS struct {
	AllowOrigin      string
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	AllowCredentials bool
	MaxAge           int // in seconds
}

CORS contains options to CORS.

type Context

type Context struct {
	W    http.ResponseWriter
	R    *http.Request
	URL  *URL
	Form *Form
	// contains filtered or unexported fields
}

A Context to handle http requests.

func (*Context) ACLUser added in v0.6.0

func (ctx *Context) ACLUser() ACLUser

ACLUser returns the acl user

func (*Context) AddHeader added in v0.1.5

func (ctx *Context) AddHeader(key string, value string)

AddHeader adds the key, value pair to the header of response writer.

func (*Context) BasicUser added in v0.4.0

func (ctx *Context) BasicUser() interface{}

BasicUser returns the basic user

func (*Context) Content added in v0.9.10

func (ctx *Context) Content(name string, modtime time.Time, content io.ReadSeeker)

Content replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

func (*Context) End

func (ctx *Context) End(status int, a ...string)

End replies to the request the status.

func (*Context) Error

func (ctx *Context) Error(message string, status int)

Error replies to the request a internal server error. if debug is enable, replies the error message.

func (*Context) File added in v0.4.0

func (ctx *Context) File(name string)

File replies to the request with the contents of the named file or directory.

func (*Context) GetCookie added in v0.1.9

func (ctx *Context) GetCookie(name string) (cookie *http.Cookie, err error)

GetCookie returns the cookie by name.

func (*Context) GetValue added in v0.11.0

func (ctx *Context) GetValue(key string) (interface{}, bool)

GetValue returns the value stored in the values for a key, or nil if no value is present.

func (*Context) HTML added in v0.7.3

func (ctx *Context) HTML(html string)

HTML replies to the request as a html.

func (*Context) IfModified added in v0.2.1

func (ctx *Context) IfModified(modtime time.Time, then func())

IfModified handles caches by modified date.

func (*Context) IfNotMatch added in v0.5.0

func (ctx *Context) IfNotMatch(etag string, then func())

IfNotMatch handles caches by etag.

func (*Context) JSON added in v0.7.3

func (ctx *Context) JSON(v interface{})

JSON replies to the request as a json.

func (*Context) Next added in v0.4.0

func (ctx *Context) Next()

Next calls the next handle.

func (*Context) Ok added in v0.4.0

func (ctx *Context) Ok(text string)

Ok replies to the request the plain text with 200 status.

func (*Context) Redirect

func (ctx *Context) Redirect(url string, status int)

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

func (*Context) RemoteIP

func (ctx *Context) RemoteIP() string

RemoteIP returns the remote client IP

func (*Context) RemoveCookie

func (ctx *Context) RemoveCookie(cookie *http.Cookie)

RemoveCookie removes the cookie.

func (*Context) RemoveCookieByName added in v0.8.0

func (ctx *Context) RemoveCookieByName(name string)

RemoveCookieByName removes the cookie by name.

func (*Context) Render added in v0.5.0

func (ctx *Context) Render(template Template, data interface{})

Render applies a parsed template with the specified data object, replies to the request.

func (*Context) RenderHTML added in v0.5.8

func (ctx *Context) RenderHTML(html string, data interface{})

RenderHTML applies a unparsed html template with the specified data object, replies to the request.

func (*Context) Session

func (ctx *Context) Session() *Session

Session returns the session if it is undefined then create a new one.

func (*Context) SetACLUser added in v0.9.2

func (ctx *Context) SetACLUser(user ACLUser)

SetACLUser sets the acl user

func (*Context) SetCookie

func (ctx *Context) SetCookie(cookie *http.Cookie)

SetCookie sets a cookie.

func (*Context) SetHeader added in v0.1.5

func (ctx *Context) SetHeader(key string, value string)

SetHeader sets the header of response writer entries associated with key to the single element value.

func (*Context) StoreValue added in v0.9.2

func (ctx *Context) StoreValue(key string, value interface{})

StoreValue sets the value for a key.

func (*Context) Write

func (ctx *Context) Write(p []byte) (n int, err error)

Write implements the io.Writer.

type Form added in v0.11.0

type Form struct {
	R *http.Request
}

A Form to handle http form

func (*Form) Default added in v0.11.0

func (form *Form) Default(key string, defaultValue string) string

Default returns the defaultValue if the form value is empty

func (*Form) File added in v0.11.0

func (form *Form) File(key string) (multipart.File, *multipart.FileHeader, error)

File returns the first file for the provided form key.

func (*Form) Float added in v0.11.1

func (form *Form) Float(key string) (float64, error)

Float returns the form value as float

func (*Form) Int added in v0.11.1

func (form *Form) Int(key string) (int64, error)

Int returns the form value as integer

func (*Form) Require added in v0.11.0

func (form *Form) Require(key string) string

Require requires a value

func (*Form) RequireFloat added in v0.11.0

func (form *Form) RequireFloat(key string) float64

RequireFloat requires a value as float

func (*Form) RequireInt added in v0.11.0

func (form *Form) RequireInt(key string) int64

RequireInt requires a value as int

func (*Form) Value added in v0.11.0

func (form *Form) Value(key string) string

Value returns the first value for the named component of the POST, PATCH, or PUT request body, or returns the first value for the named component of the request url query.

type Handle added in v0.8.0

type Handle func(ctx *Context)

Handle defines a REST handle

func ACL added in v0.5.1

func ACL(permissions ...string) Handle

ACL returns a ACL middleware.

func AccessLogger added in v0.13.2

func AccessLogger(logger Logger) Handle

AccessLogger returns a AccessLogger middleware to sets the access logger.

func BasicAuth added in v0.4.0

func BasicAuth(auth func(name string, password string) (user interface{}, err error)) Handle

BasicAuth returns a Basic HTTP Authorization middleware.

func BasicAuthWithRealm added in v0.8.0

func BasicAuthWithRealm(realm string, auth func(name string, password string) (user interface{}, err error)) Handle

BasicAuthWithRealm returns a Basic HTTP Authorization middleware with realm.

func Cors added in v0.13.2

func Cors(cors CORS) Handle

Cors returns a Cors middleware to handle cors.

func ErrorLogger added in v0.13.2

func ErrorLogger(logger Logger) Handle

ErrorLogger returns a ErrorLogger middleware to sets the error logger.

func Header(key string, value string) Handle

Header is REX middleware to set http header

func JSONError added in v0.13.2

func JSONError() Handle

JSONError returns a JSONError middleware to pass error as json.

func SIDStore added in v0.6.2

func SIDStore(sidStore session.SIDStore) Handle

SIDStore returns a SIDStore middleware to sets sid store for session.

func SendError added in v0.13.2

func SendError() Handle

SendError returns a SendError middleware.

func SessionPool added in v0.9.4

func SessionPool(pool session.Pool) Handle

SessionPool returns a SessionPool middleware to set the session pool.

type Logger added in v0.5.0

type Logger interface {
	Print(v ...interface{})
	Printf(format string, v ...interface{})
}

Logger is a logger contains Print and Printf methods.

type REST added in v0.4.0

type REST struct {
	// BasePath to add base path at beginning of each route path
	// for example if the BasePath equals "/v2", the given route path "/path" will route "/v2/path"
	BasePath string
	// contains filtered or unexported fields
}

REST is REST-based router

func Group added in v0.9.3

func Group(path string, callback func(*REST)) *REST

Group creates a nested REST

func New added in v0.4.0

func New(base string) *REST

New returns a new REST

func (*REST) Delete added in v0.4.0

func (rest *REST) Delete(path string, handles ...Handle)

Delete is a shortcut for rest.Handle("DELETE", path, handles)

func (*REST) Get added in v0.4.0

func (rest *REST) Get(path string, handles ...Handle)

Get is a shortcut for rest.Handle("GET", path, handles)

func (*REST) Group added in v0.9.0

func (rest *REST) Group(path string, callback func(*REST)) *REST

Group creates a nested REST

func (*REST) Handle added in v0.4.0

func (rest *REST) Handle(method string, path string, handles ...Handle)

Handle handles requests that match the method and path

func (*REST) Head added in v0.4.0

func (rest *REST) Head(path string, handles ...Handle)

Head is a shortcut for rest.Handle("HEAD", path, handles)

func (*REST) NotFound added in v0.5.0

func (rest *REST) NotFound(handle Handle)

NotFound sets a NotFound handle.

func (*REST) Options added in v0.4.0

func (rest *REST) Options(path string, handles ...Handle)

Options is a shortcut for rest.Handle("OPTIONS", path, handles)

func (*REST) Patch added in v0.4.0

func (rest *REST) Patch(path string, handles ...Handle)

Patch is a shortcut for rest.Handle("PATCH", path, handles)

func (*REST) Post added in v0.4.0

func (rest *REST) Post(path string, handles ...Handle)

Post is a shortcut for rest.Handle("POST", path, handles)

func (*REST) Put added in v0.4.0

func (rest *REST) Put(path string, handles ...Handle)

Put is a shortcut for rest.Handle("PUT", path, handles)

func (*REST) ServeHTTP added in v0.5.0

func (rest *REST) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*REST) Static added in v0.12.8

func (rest *REST) Static(path string, root string, fallbackPath ...string)

Static handles static files requests.

func (*REST) Trace added in v0.9.8

func (rest *REST) Trace(path string, handles ...Handle)

Trace is a shortcut for rest.Handle("TRACE", path, handles)

func (*REST) Use added in v0.4.0

func (rest *REST) Use(middlewares ...Handle)

Use appends middlewares to current REST middleware stack.

type ServerConfig added in v0.12.5

type ServerConfig struct {
	Port           uint16    `json:"port"`
	TLS            TLSConfig `json:"tls"`
	ReadTimeout    uint32    `json:"readTimeout"`
	WriteTimeout   uint32    `json:"writeTimeout"`
	MaxHeaderBytes uint32    `json:"maxHeaderBytes"`
}

ServerConfig contains options to run the REX server.

type Session added in v0.5.1

type Session struct {
	session.Session
}

Session handles session

func (*Session) Delete added in v0.5.1

func (s *Session) Delete(key string)

Delete removes a session value

func (*Session) Flush added in v0.5.1

func (s *Session) Flush()

Flush flushes all session values

func (*Session) Get added in v0.5.1

func (s *Session) Get(key string) interface{}

Get returns a session value

func (*Session) Has added in v0.5.1

func (s *Session) Has(key string) bool

Has checks a value exists

func (*Session) SID added in v0.5.1

func (s *Session) SID() string

SID returns the sid

func (*Session) Set added in v0.5.1

func (s *Session) Set(key string, value interface{})

Set sets a session value

type TLSConfig added in v0.9.0

type TLSConfig struct {
	Port         uint16        `json:"port"`
	CertFile     string        `json:"certFile"`
	KeyFile      string        `json:"keyFile"`
	AutoTLS      AutoTLSConfig `json:"autotls"`
	AutoRedirect bool          `json:"autoRedirect"`
}

TLSConfig contains options to support https.

type Template added in v0.5.8

type Template interface {
	Execute(wr io.Writer, data interface{}) error
}

Template is a template contains an Execute method.

type URL

type URL struct {
	Params    router.Params
	RoutePath string
	*url.URL
}

A URL is a *url.URL with router.Params and RoutePath

func (*URL) Param added in v0.4.0

func (url *URL) Param(name string) string

Param returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

Directories

Path Synopsis
examples
basic-auth command
group-router command
hello command
json command
not-found command
session command
static command
todos command
zip command

Jump to

Keyboard shortcuts

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