rex

package module
v1.14.3 Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2024 License: MIT Imports: 28 Imported by: 1

README

REX

GoDoc GoReport MIT

REX is a lightweight, high-performance, and middleware-extensible web framework in Go. Used by esm.sh project.

Installation

go get -u github.com/ije/rex

Usage

package main

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

func main() {
  // use middlewares
  rex.Use(
    rex.Logger(log.Default()),
    rex.Cors(rex.CorsAll()),
    rex.Compress(),
  )

  // match "GET /" route
  rex.GET("/{$}", func(ctx *rex.Context) any {
    return rex.Render(
      rex.Tpl("<h1>My Blog</h1><ul>{{range .}}<li>{{.Title}}</li>{{end}}</ul>"),
      posts.List(),
    )
  })

  // match "GET /posts/:id" route
  rex.GET("/posts/{id}", func(ctx *rex.Context) any {
    post, ok := posts.Get(ctx.PathValue("id"))
    if !ok {
      return rex.Err(404, "post not found")
    }
    return post
  })

  // match "POST /posts" route
  rex.POST("/posts", func(ctx *rex.Context) any {
    return posts.Add(ctx.FormValue("title"), ctx.FormValue("author"), ctx.FormValue("content"))
  })

  // match "DELETE /posts/:id" route
  rex.DELETE("/posts/{id}", func(ctx *rex.Context) any {
    ok := posts.Delete(ctx.PathValue("id"))
    return ok
  })

  // Starts the server
  <-rex.Start(80)

  // Starts the server with TLS (powered by Let's Encrypt)
  <-rex.StartWithAutoTLS(443)
}

More usages please check examples/.

Middleware

In REX, a middleware is a function that receives a *rex.Context and returns a any. If the returned value is not rex.Next(), the middleware will return the value to the client, or continue to execute the next middleware.

rex.Use(func(ctx *rex.Context) any {
  // return a html response
  return rex.HTML("<h1>hello world</h1>")

  // continue next middleware
  return rex.Next()
})

Routing

REX uses ServeMux Patterns (requires Go 1.22+) to define routes.

Patterns can match the method, host and path of a request. Some examples:

  • /index.html matches the path /index.html for any host and method.
  • GET /static/ matches a GET request whose path begins with /static/.
  • example.com/ matches any request to the host example.com.
  • example.com/{$} matches requests with host example.com and path /.
  • /b/{bucket}/o/{objectname...} matches paths whose first segment is b and whose third segment is o. The name bucket denotes the second segment and objectname denotes the remainder of the path.

In general, a pattern looks like:

[METHOD ][HOST]/[PATH]

You can access the path params via the ctx.PathValue():

rex.GET("/posts/{id}", func(ctx *rex.Context) any {
  return fmt.Sprintf("ID is %s", ctx.PathValue("id"))
})

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 AddRoute added in v1.10.1

func AddRoute(pattern string, handle Handle)

AddRoute adds a route.

func Content added in v1.0.0

func Content(name string, mtime time.Time, r io.Reader) any

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

func DELETE added in v1.9.0

func DELETE(pattern string, handles ...Handle)

DELETE returns a Handle to handle DELETE requests

func Err added in v1.3.0

func Err(status int, v ...string) any

Err returns an error with status.

func FS added in v1.0.1

func FS(root string, fallback string) any

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

File replies to the request using the file content.

func GET added in v1.9.0

func GET(pattern string, handles ...Handle)

GET returns a Handle to handle GET requests

func HEAD(pattern string, handles ...Handle)

HEAD returns a Handle to handle HEAD requests

func HTML added in v1.0.0

func HTML(html string) any

HTML replies to the request with a html content.

func Next added in v1.14.0

func Next() any

Next executes the next middleware in the chain.

func NoContent added in v1.13.8

func NoContent() any

NoContent replies to the request with no content.

func PATCH added in v1.9.0

func PATCH(pattern string, handles ...Handle)

PATCH returns a Handle to handle PATCH requests

func POST added in v1.9.0

func POST(pattern string, handles ...Handle)

POST returns a Handle to handle POST requests

func PUT added in v1.9.0

func PUT(pattern string, handles ...Handle)

PUT returns a Handle to handle PUT requests

func Redirect added in v1.0.0

func Redirect(url string, status int) any

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

func Render added in v1.0.0

func Render(t Template, data any) any

Render renders the template with the given data.

func Serve

func Serve(config ServerConfig) chan error

Serve serves a REX server.

func Start added in v0.9.0

func Start(port uint16) chan error

Start starts a REX server.

func StartWithAutoTLS added in v1.9.1

func StartWithAutoTLS(port uint16, hosts ...string) chan error

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

func StartWithTLS added in v1.9.1

func StartWithTLS(port uint16, certFile string, keyFile string) chan error

StartWithTLS starts a REX server with TLS.

func Status added in v1.1.1

func Status(code int, content any) any

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 v1.12.1

type AclUser interface {
	Perms() []string
}

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

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 Context

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

A Context to handle http requests.

func (*Context) AclUser added in v1.12.2

func (ctx *Context) AclUser() AclUser

AclUser returns the ACL user

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)

Cookie returns the request cookie by name.

func (*Context) DeleteCookie added in v1.14.0

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

DeleteCookie sets a cookie to the response with an expiration time in the past.

func (*Context) DeleteCookieByName added in v1.14.0

func (ctx *Context) DeleteCookieByName(name string)

DeleteCookieByName sets a cookie to the response with an expiration time in the past.

func (*Context) FormFile added in v0.7.5

func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile returns the first file for the provided form key. FormFile calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary.

func (*Context) FormValue added in v0.6.1

func (ctx *Context) FormValue(key string) string

FormValue returns the first value for the named component of the query. The precedence order:

  1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only)
  2. query parameters (always)
  3. multipart/form-data form body (always)

FormValue calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary and ignores any errors returned by these functions. If key is not present, FormValue returns the empty string. To access multiple values of the same key, call ParseForm and then inspect [Request.Form] directly.

func (*Context) Next added in v0.4.0

func (ctx *Context) Next() any

Next executes the next middleware in the chain.

func (*Context) ParseForm added in v1.12.0

func (ctx *Context) ParseForm() error

ParseForm populates r.Form and r.PostForm.

For all requests, ParseForm parses the raw query from the URL and updates r.Form.

For POST, PUT, and PATCH requests, it also reads the request body, parses it as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form.

If the request Body's size has not already been limited by [MaxBytesReader], the size is capped at 10MB.

For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.

[Request.ParseMultipartForm] calls ParseForm automatically. ParseForm is idempotent.

func (*Context) ParseMultipartForm

func (ctx *Context) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files. ParseMultipartForm calls [Request.ParseForm] if necessary. If ParseForm returns an error, ParseMultipartForm returns it but also continues parsing the request body. After one call to ParseMultipartForm, subsequent calls have no effect.

func (*Context) PathValue added in v1.12.0

func (ctx *Context) PathValue(key string) string

PathValue returns the value for the named path wildcard in the [ServeMux] pattern that matched the request. It returns the empty string if the request was not matched against a pattern or there is no such wildcard in the pattern.

func (*Context) Pathname added in v1.12.1

func (ctx *Context) Pathname() string

Pathname returns the request pathname.

func (*Context) PostFormValue added in v1.12.0

func (ctx *Context) PostFormValue(key string) string

PostFormValue returns the first value for the named component of the POST, PUT, or PATCH request body. URL query parameters are ignored. PostFormValue calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary and ignores any errors returned by these functions. If key is not present, PostFormValue returns the empty string.

func (*Context) Query added in v1.12.1

func (ctx *Context) Query() url.Values

Query returns the request query values.

func (*Context) RemoteIP

func (ctx *Context) RemoteIP() string

RemoteIP returns the remote client IP.

func (*Context) Session

func (ctx *Context) Session() *SessionStub

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

func (*Context) SetCookie

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

SetCookie sets a cookie to the response.

func (*Context) SetPathValue added in v1.12.0

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

SetPathValue sets name to value, so that subsequent calls to r.PathValue(name) return value.

func (*Context) UserAgent added in v1.12.4

func (ctx *Context) UserAgent() string

UserAgent returns the request User-Agent.

type CorsOptions added in v1.8.0

type CorsOptions struct {
	// AllowedOrigins is a list of origins a cross-domain request can be executed from.
	// If the special "*" value is present in the list, all origins will be allowed.
	// An origin may contain a wildcard (*) to replace 0 or more characters
	// (i.e.: http://*.domain.com). Usage of wildcards implies a small performance penalty.
	// Only one wildcard can be used per origin.
	// Default value is ["*"]
	AllowedOrigins []string
	// AllowOriginFunc is a custom function to validate the origin. It take the
	// origin as argument and returns true if allowed or false otherwise. If
	// this option is set, the content of `AllowedOrigins` is ignored.
	AllowOriginFunc func(origin string) bool
	// AllowOriginRequestFunc is a custom function to validate the origin. It
	// takes the HTTP Request object and the origin as argument and returns true
	// if allowed or false otherwise. If headers are used take the decision,
	// consider using AllowOriginVaryRequestFunc instead. If this option is set,
	// the content of `AllowedOrigins`, `AllowOriginFunc` are ignored.
	AllowOriginRequestFunc func(r *http.Request, origin string) bool
	// AllowOriginVaryRequestFunc is a custom function to validate the origin.
	// It takes the HTTP Request object and the origin as argument and returns
	// true if allowed or false otherwise with a list of headers used to take
	// that decision if any so they can be added to the Vary header. If this
	// option is set, the content of `AllowedOrigins`, `AllowOriginFunc` and
	// `AllowOriginRequestFunc` are ignored.
	AllowOriginVaryRequestFunc func(r *http.Request, origin string) (bool, []string)
	// AllowedMethods is a list of methods the client is allowed to use with
	// cross-domain requests. Default value is simple methods (HEAD, GET and POST).
	AllowedMethods []string
	// AllowedHeaders is list of non simple headers the client is allowed to use with
	// cross-domain requests.
	// If the special "*" value is present in the list, all headers will be allowed.
	// Default value is [].
	AllowedHeaders []string
	// ExposedHeaders indicates which headers are safe to expose to the API of a CORS
	// API specification
	ExposedHeaders []string
	// MaxAge indicates how long (in seconds) the results of a preflight request
	// can be cached. Default value is 0, which stands for no
	// Access-Control-Max-Age header to be sent back, resulting in browsers
	// using their default value (5s by spec). If you need to force a 0 max-age,
	// set `MaxAge` to a negative value (ie: -1).
	MaxAge int
	// AllowCredentials indicates whether the request can include user credentials like
	// cookies, HTTP authentication or client side SSL certificates.
	AllowCredentials bool
	// AllowPrivateNetwork indicates whether to accept cross-origin requests over a
	// private network.
	AllowPrivateNetwork bool
	// OptionsPassthrough instructs preflight to let other potential next handlers to
	// process the OPTIONS method. Turn this on if your application handles OPTIONS.
	OptionsPassthrough bool
	// Provides a status code to use for successful OPTIONS requests.
	// Default value is http.StatusNoContent (204).
	OptionsSuccessStatus int
	// Debugging flag adds additional output to debug server side CORS issues
	Debug bool
	// Adds a custom logger, implies Debug is true
	Logger ILogger
}

CorsOptions is a configuration container to setup the CorsOptions middleware.

func CorsAll added in v1.12.1

func CorsAll() CorsOptions

CorsAll create a new Cors handler with permissive configuration allowing all origins with all standard methods with any header and credentials.

type Error added in v1.0.0

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

Error defines an error with status.

type Handle added in v0.8.0

type Handle func(ctx *Context) any

Handle defines the API handle

func AccessLogger added in v0.13.2

func AccessLogger(logger ILogger) Handle

AccessLogger returns a logger middleware to sets the access logger.

func AclAuth added in v1.12.1

func AclAuth(auth func(ctx *Context) AclUser) Handle

AclAuth returns a ACL authorization middleware.

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 Chain added in v1.10.3

func Chain(middlewares ...Handle) Handle

Chain returns a middleware handler that executes handlers in a chain.

func Compress added in v1.12.1

func Compress() Handle

Compress returns a rex middleware to enable http compression.

func Cors added in v0.13.2

func Cors(c CorsOptions) Handle

Cors returns a CORS middleware to handle CORS.

func Header(key string, value string) Handle

Header is rex middleware to set http header for the current request.

func Logger added in v0.5.0

func Logger(logger ILogger) Handle

Logger returns a logger middleware to sets the error logger for the context.

func Optional added in v1.12.5

func Optional(handle Handle, condition bool) Handle

Optional returns a middleware handler that executes the given handler only if the condition is true.

func Perm added in v1.12.2

func Perm(perms ...string) Handle

Perm returns a ACL middleware that sets the permission for the current request.

func Session added in v0.5.1

func Session(opts SessionOptions) Handle

Session returns a session middleware to configure the session manager.

func Static added in v0.5.0

func Static(root, fallback string) Handle

Static returns a static file server middleware.

type ILogger added in v1.12.1

type ILogger interface {
	Printf(format string, v ...any)
}

A ILogger interface contains the Printf method.

type Mux

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

Mux is a http.Handler with middlewares and routes.

func New added in v0.4.0

func New() *Mux

New returns a new Mux.

func (*Mux) AddRoute added in v1.12.0

func (a *Mux) AddRoute(pattern string, handle Handle)

AddRoute adds a route.

func (*Mux) ServeHTTP

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

ServeHTTP implements the http Handler.

func (*Mux) Use added in v1.12.0

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

Use appends middlewares to current APIS middleware stack.

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 SessionOptions added in v1.9.2

type SessionOptions struct {
	IdHandler session.SidHandler
	Pool      session.Pool
}

SessionOptions contains the options for the session manager.

type SessionStub added in v1.9.2

type SessionStub struct {
	session.Session
}

SessionStub is a stub for a session

func (*SessionStub) Delete added in v1.9.2

func (s *SessionStub) Delete(key string)

Delete removes a session value

func (*SessionStub) Flush added in v1.9.2

func (s *SessionStub) Flush()

Flush flushes all session values

func (*SessionStub) Get added in v1.9.2

func (s *SessionStub) Get(key string) []byte

Get returns a session value

func (*SessionStub) Has added in v1.9.2

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

Has checks a value exists

func (*SessionStub) SID added in v1.9.2

func (s *SessionStub) SID() string

SID returns the sid

func (*SessionStub) Set added in v1.9.2

func (s *SessionStub) Set(key string, value []byte)

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 {
	Name() string
	Execute(wr io.Writer, data any) error
}

Template is an interface for template.

func Tpl added in v1.4.0

func Tpl(text string) Template

Directories

Path Synopsis
examples
books command
static-site command
todos command

Jump to

Keyboard shortcuts

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