zoox

package module
v1.3.17 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2022 License: MIT Imports: 37 Imported by: 58

README

Zoox - A Lightweight Web Framework

PkgGoDev Build Status Go Report Card Coverage Status GitHub issues Release

Installation

To install the package, run:

go get github.com/go-zoox/zoox

Getting Started

package main

import "github.com/go-zoox/zoox"

func main() {
	app := zoox.Default()

	app.Get("/", func(ctx *zoox.Context) {
		ctx.Write([]byte("helloworld"))
	})

	app.Run(":8080")
}

License

GoZoox is released under the MIT License.

Documentation

Index

Constants

View Source
const DebugEnv = "GO_ZOOX_DEBUG"

DebugEnv is the environment variable name for debug.

View Source
const HeaderContentType = "Content-Type"

HeaderContentType ...

Variables

View Source
var DefaultGroupsFns = map[string]func(r *RouterGroup){}

DefaultGroupsFns ...

View Source
var DefaultMiddlewares = map[string]func(app *Application){}

DefaultMiddlewares is the default global middleware

View Source
var RequestIDHeader = "X-Request-Id"

RequestIDHeader is the name of the header that contains the request ID.

View Source
var Version = "1.3.17"

Version is the current version of the package.

Functions

func DefaultGroup added in v1.0.16

func DefaultGroup(prefix string, fn func(r *RouterGroup))

DefaultGroup ...

func DefaultMiddleware added in v1.0.16

func DefaultMiddleware(name string, fn func(app *Application))

DefaultMiddleware ...

func GenerateRequestID added in v1.2.1

func GenerateRequestID() string

GenerateRequestID generates a unique request ID.

Types

type Application

type Application struct {
	*RouterGroup

	//
	SecretKey string
	LogLevel  string
	//
	CacheConfig *typing.Config

	//
	Env    *Env
	Logger *logger.Logger
	// contains filtered or unexported fields
}

Application is the handler for all requests.

func New

func New() *Application

New is the constructor of zoox.Application.

func (*Application) Cache added in v1.0.24

func (app *Application) Cache() *Cache

Cache ...

func (*Application) CreateJSONRPC added in v1.2.0

func (app *Application) CreateJSONRPC(path string) jsonrpc.Server[*Context]

CreateJSONRPC creates a new CreateJSONRPC handler.

func (*Application) Cron added in v1.3.3

func (app *Application) Cron() *Cron

Cron ...

func (*Application) Debug added in v1.2.4

func (app *Application) Debug() *Debug

Debug ...

func (*Application) Fallback

func (app *Application) Fallback(h HandlerFunc)

Fallback is the default handler for all requests.

func (*Application) IsProd added in v1.1.0

func (app *Application) IsProd() bool

IsProd returns true if the app is in production mode.

func (*Application) NotFound

func (app *Application) NotFound(h HandlerFunc)

NotFound defines the 404 handler, replaced of built in not found handler.

func (*Application) Queue added in v1.3.3

func (app *Application) Queue() *Queue

Queue ...

func (*Application) Run

func (app *Application) Run(addr ...string) error

Run defines the method to start the server

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Application) SetTemplates

func (app *Application) SetTemplates(dir string, fns ...template.FuncMap)

SetTemplates set the template

type Body added in v1.3.12

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

Body ...

func (*Body) Get added in v1.3.12

func (f *Body) Get(key string, defaultValue ...interface{}) interface{}

Get gets request form with the given name.

type Cache added in v1.0.24

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

Cache ...

func (*Cache) Del added in v1.0.24

func (c *Cache) Del(key string) error

Del ...

func (*Cache) Get added in v1.0.24

func (c *Cache) Get(key string, value interface{}) error

Get ...

func (*Cache) Set added in v1.0.24

func (c *Cache) Set(key string, value interface{}, ttl time.Duration) error

Set ...

type Context

type Context struct {
	// origin objects
	Writer  ResponseWriter
	Request *http.Request
	// request
	Method string
	Path   string

	// response
	StatusCode int

	//
	App *Application
	//
	Logger *logger.Logger
	// contains filtered or unexported fields
}

Context is the request context

func (*Context) AcceptHTML added in v1.3.12

func (ctx *Context) AcceptHTML() bool

AcceptHTML returns true if the request accepts html.

func (*Context) AcceptJSON added in v1.0.19

func (ctx *Context) AcceptJSON() bool

AcceptJSON returns true if the request accepts json.

func (*Context) AddHeader added in v1.0.6

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

AddHeader adds a header to the response.

func (*Context) Authorization added in v1.3.16

func (ctx *Context) Authorization() string

Authorization returns the authorization header for auth.

func (*Context) BasicAuth added in v1.0.1

func (ctx *Context) BasicAuth() (username string, password string, ok bool)

BasicAuth returns the user/password pair for Basic Authentication.

func (*Context) BearerToken added in v1.3.16

func (ctx *Context) BearerToken() (token string, ok bool)

BearerToken returns the token for bearer authentication.

func (*Context) BindForm added in v1.0.1

func (ctx *Context) BindForm(obj interface{}) error

BindForm binds the query into the given struct.

func (*Context) BindHeader added in v1.0.1

func (ctx *Context) BindHeader(obj interface{}) error

BindHeader binds the header into the given struct.

func (*Context) BindJSON added in v1.0.1

func (ctx *Context) BindJSON(obj interface{}) error

BindJSON binds the request body into the given struct.

func (*Context) BindParams added in v1.0.1

func (ctx *Context) BindParams(obj interface{}) error

BindParams binds the params into the given struct.

func (*Context) BindQuery added in v1.0.1

func (ctx *Context) BindQuery(obj interface{}) error

BindQuery binds the query into the given struct.

func (*Context) BindYAML added in v1.0.1

func (ctx *Context) BindYAML(obj interface{}) error

BindYAML binds the request body into the given struct.

func (*Context) Bodies added in v1.0.1

func (ctx *Context) Bodies() map[string]any

Bodies gets all bodies.

func (*Context) Body added in v1.3.12

func (ctx *Context) Body() *Body

Body returns the request body.

func (*Context) Cache added in v1.0.24

func (ctx *Context) Cache() *Cache

Cache returns the cache of the application.

func (*Context) Cookie added in v1.0.1

func (ctx *Context) Cookie() *Cookie

Cookie returns the cookie of the request.

func (*Context) Cookies added in v1.0.1

func (ctx *Context) Cookies() map[string]string

Cookies gets all cookies.

func (*Context) Cron added in v1.3.3

func (ctx *Context) Cron() *Cron

Cron returns the cache of the application.

func (*Context) Data added in v1.2.19

func (ctx *Context) Data(status int, contentType string, data []byte)

Data writes some data into the body stream and updates the HTTP code. Align to gin framework.

func (*Context) Debug added in v1.2.4

func (ctx *Context) Debug() *Debug

Debug returns the debug of the app.

func (*Context) Env added in v1.0.17

func (ctx *Context) Env() *Env

Env returns the env of the

func (*Context) Error

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

Error writes the given error to the response. Use for system errors

  1. Internal server error
  2. Not found

func (*Context) Fail

func (ctx *Context) Fail(err error, code int, message string, status ...int)

Fail writes the given error with code-message-result specification to the response.

func (*Context) FailWithError added in v1.1.0

func (ctx *Context) FailWithError(err HTTPError)

FailWithError writes the given error with code-message-result specification to the response.

func (*Context) Fetch added in v1.3.1

func (ctx *Context) Fetch() *fetch.Fetch

Fetch is the context request utils, based on go-zoox/fetch.

func (*Context) File added in v1.0.1

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

File gets the file by key.

func (*Context) Files added in v1.0.1

func (ctx *Context) Files() map[string]*multipart.FileHeader

Files gets all files.

func (*Context) Form added in v1.0.5

func (ctx *Context) Form() *Form

Form returns the form data from POST or PUT request body.

func (*Context) Forms added in v1.0.1

func (ctx *Context) Forms() *safe.Map

Forms gets all forms.

func (*Context) Get added in v1.0.20

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

Get alias for ctx.Header.

func (*Context) GetRawData added in v1.2.19

func (ctx *Context) GetRawData() ([]byte, error)

GetRawData returns stream data. Align to gin framework.

func (*Context) HTML

func (ctx *Context) HTML(code int, name string, data interface{})

HTML renders the given template with the given data and writes the result

func (*Context) Header added in v1.0.1

func (ctx *Context) Header() http.Header

Header gets the header value by key.

func (*Context) Headers added in v1.0.1

func (ctx *Context) Headers() *safe.Map

Headers gets all headers.

func (*Context) Host added in v1.0.4

func (ctx *Context) Host() string

Host gets the host from HTTP Header. format: `host:port`

func (*Context) IP added in v1.0.4

func (ctx *Context) IP() string

IP gets the ip from X-Forwarded-For or X-Real-IP or RemoteAddr.

func (*Context) JSON

func (ctx *Context) JSON(status int, obj interface{})

JSON serializes the given struct as JSON into the response body.

func (*Context) Next

func (ctx *Context) Next()

Next runs the next handler in the middleware stack

func (*Context) Origin added in v1.0.20

func (ctx *Context) Origin() string

Origin returns the origin of the request.

func (*Context) Param

func (ctx *Context) Param() *Param

Param returns the named URL parameter value if it exists.

func (*Context) Params

func (ctx *Context) Params() *safe.Map

Params gets all params.

func (*Context) Protocol added in v1.3.16

func (ctx *Context) Protocol() string

Protocol returns the protocol, usally http or https

func (*Context) Queries added in v1.0.1

func (ctx *Context) Queries() *safe.Map

Queries gets all queries.

func (*Context) Query

func (ctx *Context) Query() *Query

Query returns the query string parameter with the given name.

func (*Context) Queue added in v1.3.3

func (ctx *Context) Queue() *Queue

Queue returns the queue of the application.

func (*Context) Redirect

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

Redirect redirects the request to the given URL.

func (*Context) Render

func (ctx *Context) Render(code int, name string, data interface{})

Render renders a template with data and writes the result to the response.

func (*Context) RequestID added in v1.1.2

func (ctx *Context) RequestID() string

RequestID returns the request id of the request.

func (*Context) SaveFile added in v1.0.1

func (ctx *Context) SaveFile(key, path string) error

SaveFile saves the file to the given path.

func (*Context) Session added in v1.0.14

func (ctx *Context) Session() *Session

Session returns the session of the request.

func (*Context) Set added in v1.0.5

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

Set alias for ctx.SetHeader.

func (*Context) SetHeader

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

SetHeader sets a header in the response.

func (*Context) State added in v1.0.6

func (ctx *Context) State() *State

State returns the state of the

func (*Context) Status

func (ctx *Context) Status(status int)

Status sets the HTTP response status code.

func (*Context) Stream added in v1.0.1

func (ctx *Context) Stream() io.ReadCloser

Stream get the body stream.

func (*Context) String

func (ctx *Context) String(status int, format string, values ...interface{})

String writes the given string to the response.

func (*Context) Success

func (ctx *Context) Success(result interface{})

Success writes the given data with code-message-result specification to the response.

func (*Context) URL added in v1.0.4

func (ctx *Context) URL() string

URL is http.Request.RequestURI.

func (*Context) User added in v1.1.0

func (ctx *Context) User() *User

User returns the user of the

func (*Context) Write

func (ctx *Context) Write(b []byte)

Write writes the data to the connection.

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

Cookie is a middleware for handling cookie.

func (*Cookie) Del added in v1.0.5

func (c *Cookie) Del(name string)

Del deletes response cookie with the given name.

func (*Cookie) Get added in v1.0.5

func (c *Cookie) Get(name string) string

Get gets request cookie with the given name.

func (*Cookie) Set added in v1.0.5

func (c *Cookie) Set(name string, value string, maxAge time.Duration)

Set sets response cookie with the given name and value.

type Cron added in v1.3.3

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

Cron ...

func (*Cron) AddDailyJob added in v1.3.3

func (c *Cron) AddDailyJob(name string, cmd func() error) (id int, err error)

AddDailyJob adds a schedule job run in every day.

func (*Cron) AddHourlyJob added in v1.3.3

func (c *Cron) AddHourlyJob(name string, cmd func() error) (id int, err error)

AddHourlyJob adds a schedule job run in every hour.

func (*Cron) AddJob added in v1.3.3

func (c *Cron) AddJob(name string, spec string, job func() error) (id int, err error)

AddJob ...

func (*Cron) AddMinutelyJob added in v1.3.3

func (c *Cron) AddMinutelyJob(name string, cmd func() error) (id int, err error)

AddMinutelyJob adds a schedule job run in every minute.

func (*Cron) AddMonthlyJob added in v1.3.3

func (c *Cron) AddMonthlyJob(name string, cmd func() error) (id int, err error)

AddMonthlyJob adds a schedule job run in every month.

func (*Cron) AddSecondlyJob added in v1.3.3

func (c *Cron) AddSecondlyJob(name string, cmd func() error) (id int, err error)

AddSecondlyJob adds a schedule job run in every second.

func (*Cron) AddWeeklyJob added in v1.3.3

func (c *Cron) AddWeeklyJob(name string, cmd func() error) (id int, err error)

AddWeeklyJob adds a schedule job run in every week.

func (*Cron) AddYearlyJob added in v1.3.3

func (c *Cron) AddYearlyJob(name string, cmd func() error) (id int, err error)

AddYearlyJob adds a schedule job run in every year.

func (*Cron) ClearJobs added in v1.3.17

func (c *Cron) ClearJobs() error

ClearJobs clears all jobs.

func (*Cron) RemoveJob added in v1.3.17

func (c *Cron) RemoveJob(id int) error

RemoveJob ...

type Debug added in v1.2.4

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

Debug ...

func (*Debug) Info added in v1.2.4

func (c *Debug) Info(args ...interface{})

Info logs debug info.

type Env added in v1.0.17

type Env struct {
}

Env ...

func (*Env) Get added in v1.0.17

func (e *Env) Get(key string) string

Get ...

type Form added in v1.1.0

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

Form ...

func (*Form) Get added in v1.1.0

func (f *Form) Get(key string, defaultValue ...string) string

Get gets request form with the given name.

type H

type H map[string]interface{}

H is a shortcut for map[string]interface{}

type HTTPError added in v1.1.0

type HTTPError interface {
	Status() int
	Code() int
	Message() string
	Error() string
	Raw() error
}

HTTPError is a custom error type for HTTP errors.

type HandlerFunc

type HandlerFunc func(ctx *Context)

HandlerFunc defines the request handler used by gee

func NotFound

func NotFound() HandlerFunc

NotFound returns a HandlerFunc that replies with a 404 not found

func WrapH

func WrapH(handler http.Handler) HandlerFunc

WrapH wraps a http.Handler to a HandlerFunc

type Middleware added in v1.0.20

type Middleware = HandlerFunc

Middleware defines the signature of the middleware function.

type Param added in v1.1.0

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

Param ...

func (*Param) Get added in v1.1.0

func (q *Param) Get(key string, defaultValue ...string) string

Get gets request param with the given name.

func (*Param) Iterator added in v1.1.0

func (q *Param) Iterator() map[string]string

Iterator ...

type Query added in v1.1.0

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

Query ...

func (*Query) Get added in v1.1.0

func (q *Query) Get(key string, defaultValue ...string) string

Get gets request query with the given name.

type Queue added in v1.3.3

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

Queue is a simple job queue.

func (*Queue) AddJob added in v1.3.3

func (q *Queue) AddJob(job jobqueue.Job) error

AddJob ...

func (*Queue) AddJobFunc added in v1.3.3

func (q *Queue) AddJobFunc(task func(), callback func(status int, err error)) error

AddJobFunc ...

type ResponseWriter added in v1.0.12

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.CloseNotifier
	http.Flusher

	// Status returns the HTTP response status code of the current request.
	Status() int

	// Size returns the number of bytes already written into the response http body.
	// See Written()
	Size() int

	// WriteString writes the string into the response body.
	WriteString(string) (int, error)

	// Written returns true if the response body was already written.
	Written() bool

	// WriteHeaderNow forces to write the http header (status code + headers).
	WriteHeaderNow()

	// Pusher get the http.Pusher for server push
	Pusher() http.Pusher
	// contains filtered or unexported methods
}

ResponseWriter ...

type RouterGroup

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

RouterGroup is a group of routes.

func (*RouterGroup) Any added in v1.0.3

func (g *RouterGroup) Any(path string, handler ...HandlerFunc) *RouterGroup

Any defines all request methods (anyMethods)

func (*RouterGroup) Delete

func (g *RouterGroup) Delete(path string, handler ...HandlerFunc) *RouterGroup

Delete defines the method to add DELETE request

func (*RouterGroup) Get

func (g *RouterGroup) Get(path string, handler ...HandlerFunc) *RouterGroup

Get defines the method to add GET request

func (*RouterGroup) Group

func (g *RouterGroup) Group(prefix string) *RouterGroup

Group defines a new router group

func (*RouterGroup) Head

func (g *RouterGroup) Head(path string, handler ...HandlerFunc) *RouterGroup

Head defines the method to add HEAD request

func (*RouterGroup) Options added in v1.0.3

func (g *RouterGroup) Options(path string, handler ...HandlerFunc) *RouterGroup

Options defines the method to add OPTIONS request

func (*RouterGroup) Patch

func (g *RouterGroup) Patch(path string, handler ...HandlerFunc) *RouterGroup

Patch defines the method to add PATCH request

func (*RouterGroup) Post

func (g *RouterGroup) Post(path string, handler ...HandlerFunc) *RouterGroup

Post defines the method to add POST request

func (*RouterGroup) Put

func (g *RouterGroup) Put(path string, handler ...HandlerFunc) *RouterGroup

Put defines the method to add PUT request

func (*RouterGroup) Static

func (g *RouterGroup) Static(relativePath string, root string, options ...StaticOptions)

Static defines the method to serve static files

func (*RouterGroup) StaticFS added in v1.0.15

func (g *RouterGroup) StaticFS(relativePath string, fs http.FileSystem)

StaticFS defines the method to serve static files

func (*RouterGroup) Use

func (g *RouterGroup) Use(middlewares ...HandlerFunc)

Use adds a middleware to the group

func (*RouterGroup) WebSocket added in v1.0.28

func (g *RouterGroup) WebSocket(path string, handler WsHandlerFunc) *RouterGroup

WebSocket defines the method to add websocket route

type Session added in v1.0.14

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

Session is the http session based on cookie.

func (*Session) Del added in v1.0.14

func (s *Session) Del(key string)

Del deletes the value by key.

func (*Session) Get added in v1.0.14

func (s *Session) Get(key string) string

Get gets the value by key.

func (*Session) Set added in v1.0.14

func (s *Session) Set(key string, value string)

Set sets the value by key.

type State added in v1.1.0

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

State is the state for request context.

func (*State) Get added in v1.1.0

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

Get gets the value from context state with the given key.

func (*State) Set added in v1.1.0

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

Set sets the value to context state with the given key.

type StaticOptions

type StaticOptions struct {
	Gzip         bool
	Md5          bool
	CacheControl string
	MaxAge       time.Duration
	Index        bool
	Suffix       string
}

StaticOptions is the options for static method

type User added in v1.1.0

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

User is the user for request context.

func (*User) Get added in v1.1.0

func (s *User) Get() interface{}

Get gets user from request context

func (*User) Set added in v1.1.0

func (s *User) Set(user interface{})

Set sets user to request context

type WebSocketClient added in v1.0.28

type WebSocketClient struct {
	OnConnect       func()
	OnDisconnect    func()
	OnMessage       func(typ int, msg []byte)
	OnTextMessage   func(msg []byte)
	OnBinaryMessage func(msg []byte)
	OnError         func(err error)
	// contains filtered or unexported fields
}

WebSocketClient ...

func (*WebSocketClient) CreateJSONRPC added in v1.2.7

func (c *WebSocketClient) CreateJSONRPC() jsonrpc.Server[any]

CreateJSONRPC ...

func (*WebSocketClient) Disconnect added in v1.0.28

func (c *WebSocketClient) Disconnect()

Disconnect ...

func (*WebSocketClient) Write added in v1.0.28

func (c *WebSocketClient) Write(typ int, msg []byte) error

Write ...

func (*WebSocketClient) WriteBinary added in v1.0.28

func (c *WebSocketClient) WriteBinary(msg []byte) error

WriteBinary ...

func (*WebSocketClient) WriteBytes added in v1.2.7

func (c *WebSocketClient) WriteBytes(msg []byte) error

WriteBytes ...

func (*WebSocketClient) WriteJSON added in v1.0.28

func (c *WebSocketClient) WriteJSON(msg interface{}) error

WriteJSON ...

func (*WebSocketClient) WriteText added in v1.0.28

func (c *WebSocketClient) WriteText(msg string) error

WriteText ...

type WsHandlerFunc added in v1.0.28

type WsHandlerFunc func(ctx *Context, client *WebSocketClient)

WsHandlerFunc defines the websocket handler used by gee

Directories

Path Synopsis
rpc

Jump to

Keyboard shortcuts

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