rex

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2021 License: MIT Imports: 24 Imported by: 1

README

REX

GoDoc GoReport MIT

REX provides a query/mutation style API server in Golang, noREST.

Installing

go get -u github.com/ije/rex

Example

package main

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

func main() {
    // GET /*
    rex.Query("*", func(ctx *rex.Context) interface{} {
        return rex.HTML(
            200,
            "<h1>My Blog</h1><ul>{{range .}}<li>{{.Title}}</li>{{end}}</ul>",
            blogs.All(),
        )
    })

    // GET /post/123 => Blog JSON
    rex.Query("post/*", func(ctx *rex.Context) interface{} {
        blog, ok := blogs.Get(ctx.Path.RequireIntSegment(1))
        if !ok {
            return &rex.Error{404, "blog not found"}
        }
        return blog
    })

    // POST /add-blog {"title": "Hello World"} => Blog JSON
    rex.Mutation("add-blog", func(ctx *rex.Context) interface{} {
        blog := NewBlog(ctx.Form.Value("title"))
        blogs.Add(blog)
        return blog
    })

    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 Content added in v1.0.0

func Content(name string, mtime time.Time, r io.ReadSeeker) *contentful

Content replies to the request using the content in the provided ReadSeeker.

func FS added in v1.0.1

func FS(root string, fallback string) interface{}

FS replies to the request with the contents of the file system rooted at root.

func File added in v1.0.0

func File(name string) *contentful

File replies to the request using the file content.

func HTML added in v1.0.0

func HTML(html string, data interface{}) *contentful

HTML replies to the request with a html content.

func Mutation added in v1.0.0

func Mutation(endpoint string, handles ...Handle)

Mutation adds a mutation api

func Query added in v1.0.0

func Query(endpoint string, handles ...Handle)

Query adds a query api

func Redirect added in v1.0.0

func Redirect(url string, status int) interface{}

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

func Serve

func Serve(config ServerConfig) chan error

Serve serves a rex server.

func Start added in v0.9.0

func Start(port uint16) (err error)

Start starts a REX server.

func StartAutoTLS added in v0.9.0

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

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) (err error)

StartTLS starts a REX server with TLS.

func Status added in v1.1.1

func Status(status int, payload interface{}) *statusPlayload

Status replies to the request using the payload in the status.

func Use added in v0.9.0

func Use(middlewares ...Handle)

Use appends middlewares to current APIS middleware stack.

Types

type ACLUser added in v0.8.1

type ACLUser interface {
	Permissions() []string
}

A ACLUser interface contains the Permissions method that returns the permission IDs

type APIHandler added in v1.0.0

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

APIHandler is a query/mutation style API http Handler

func Default added in v0.13.4

func Default() *APIHandler

Default returns the default REST

func Prefix added in v1.4.0

func Prefix(prefix string) *APIHandler

Prefix adds prefix for each api path, like "v2"

func (*APIHandler) Mutation added in v1.0.0

func (a *APIHandler) Mutation(endpoint string, handles ...Handle)

Mutation adds a mutation api

func (*APIHandler) Prefix added in v1.0.0

func (a *APIHandler) Prefix(prefix string) *APIHandler

Prefix adds prefix for each api path, like "v2"

func (*APIHandler) Query added in v1.0.0

func (a *APIHandler) Query(endpoint string, handles ...Handle)

Query adds a query api

func (*APIHandler) ServeHTTP added in v1.0.0

func (a *APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http Handler.

func (*APIHandler) Use added in v1.0.0

func (a *APIHandler) Use(middlewares ...Handle)

Use appends middlewares to current APIS middleware stack.

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 {
	AllowAllOrigins  bool
	AllowOrigins     []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
	Path  *Path
	Form  *Form
	Store *Store
	// 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) BasicAuthUser added in v0.5.0

func (ctx *Context) BasicAuthUser() string

BasicAuthUser returns the BasicAuth username

func (*Context) Cookie

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

Cookie returns the cookie by name.

func (*Context) DeleteHeader added in v0.14.0

func (ctx *Context) DeleteHeader(key string)

DeleteHeader deletes the values associated with key.

func (*Context) EnableCompression added in v1.0.2

func (ctx *Context) EnableCompression()

EnableCompression enables the compression method based on the Accept-Encoding header

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) 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.

type Error added in v1.0.0

type Error struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
}

Error defines an error with status.

func Err added in v1.3.0

func Err(status int, v ...string) *Error

type Form added in v0.11.0

type Form struct {
	R *http.Request
}

A Form to handle request form data.

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) IsNil added in v0.15.6

func (form *Form) IsNil(key string) bool

IsNil checks the value for the key whether is nil.

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) interface{}

Handle defines the API 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, secret string) (ok bool, 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, secret string) (ok bool, 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 SIDStore added in v0.6.2

func SIDStore(sidStore session.SIDStore) Handle

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

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 {
	Printf(format string, v ...interface{})
}

A Logger interface contains the Printf method.

type Path added in v1.2.0

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

A Form to handle request path.

func (*Path) GetFloatSegment added in v1.2.1

func (path *Path) GetFloatSegment(index int) (float64, error)

FloatSegment returns the path segment as float by the index

func (*Path) GetIntSegment added in v1.2.1

func (path *Path) GetIntSegment(index int) (int64, error)

IntSegment returns the path segment as int by the index

func (*Path) GetSegment added in v1.2.1

func (path *Path) GetSegment(index int) string

Segment returns the path segment by the index

func (*Path) RequireFloatSegment added in v1.2.0

func (path *Path) RequireFloatSegment(index int) float64

RequireFloatSegment requires a path segment as float by the index

func (*Path) RequireIntSegment added in v1.2.0

func (path *Path) RequireIntSegment(index int) int64

RequireIntSegment requires a path segment as int by the index

func (*Path) RequireSegment added in v1.2.0

func (path *Path) RequireSegment(index int) string

RequireSegment requires a path segment by the index

func (*Path) Segments added in v1.2.1

func (path *Path) Segments() []string

Len returns the path segments

func (*Path) String added in v1.2.0

func (path *Path) String() string

String returns the path as string

func (*Path) Update added in v1.2.1

func (path *Path) Update(pathname string)

Update sets a new path

type ServerConfig added in v0.12.5

type ServerConfig struct {
	Host           string    `json:"host"`
	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 sessions for Context

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) []byte

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 []byte)

Set sets a session value

type Store added in v1.1.0

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

A Store to store values.

func (*Store) Get added in v1.1.0

func (s *Store) Get(key string) (interface{}, bool)

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

func (*Store) Set added in v1.1.0

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

Set sets the value for a key.

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 Tpl added in v1.4.0

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

Directories

Path Synopsis
examples
static command
todos command

Jump to

Keyboard shortcuts

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