znet

package
v1.4.6 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2022 License: MIT Imports: 41 Imported by: 23

Documentation

Overview

Package znet provides web service

package main

import (
	"github.com/sohaha/zlsgo/znet"
)

func main(){
	r := znet.New()

	r.SetMode(znet.DebugMode)
	r.GET("/", func(c znet.Context) {
		c.String(200, "hello world")
	})

	znet.Run()
}

Index

Constants

View Source
const (

	// DebugMode dev
	DebugMode = "dev"
	// ProdMode release
	ProdMode = "prod"
	// TestMode test
	TestMode = "test"
	// QuietMode quiet
	QuietMode = "quiet"
)

Variables

View Source
var (
	RemoteIPHeaders = []string{"X-Forwarded-For", "X-Real-IP"}
	TrustedProxies  = []string{"0.0.0.0/0"}
	LocalNetworks   = []string{"127.0.0.0/8", "10.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "172.0.0.0/8", "192.168.0.0/16"}
)
View Source
var (
	// ContentTypePlain text
	ContentTypePlain = "text/plain; charset=utf-8"
	// ContentTypeHTML html
	ContentTypeHTML = "text/html; charset=utf-8"
	// ContentTypeJSON json
	ContentTypeJSON = "application/json; charset=utf-8"
)
View Source
var (
	// ErrGenerateParameters is returned when generating a route withRequestLog wrong parameters.
	ErrGenerateParameters = errors.New("params contains wrong parameters")

	// ErrNotFoundRoute is returned when generating a route that can not find route in tree.
	ErrNotFoundRoute = errors.New("cannot find route in tree")

	// ErrNotFoundMethod is returned when generating a route that can not find method in tree.
	ErrNotFoundMethod = errors.New("cannot find method in tree")

	// ErrPatternGrammar is returned when generating a route that pattern grammar error.
	ErrPatternGrammar = errors.New("pattern grammar error")
)
View Source
var (
	// Log Log
	Log   = zlog.New(zlog.ColorTextWrap(zlog.ColorGreen, "[Z] "))
	Cache = zcache.New("__ZNET__")
	// ShutdownDone Shutdown Done executed after shutting down the server
	ShutdownDone func()
	// CloseHotRestart Close Hot Restart
	CloseHotRestart bool

	// BindStructDelimiter structure route delimiter
	BindStructDelimiter = "-"
	// BindStructSuffix structure route suffix
	BindStructSuffix = ""
)

Functions

func ClientIP

func ClientIP(r *http.Request) (ip string)

ClientIP ClientIP

func ClientPublicIP

func ClientPublicIP(r *http.Request) string

ClientPublicIP ClientPublicIP

func CloseHotRestartFileMd5 added in v0.1.26

func CloseHotRestartFileMd5()

CloseHotRestartFileMd5 CloseHotRestartFileMd5

func CompletionPath added in v1.3.1

func CompletionPath(p, prefix string) string

func GetIPv added in v1.1.18

func GetIPv(s string) int

GetIPv GetIPv

func IPToLong added in v1.1.18

func IPToLong(ip string) (i uint, err error)

IPToLong IPToLong

func InNetwork added in v1.1.18

func InNetwork(ip, network string) bool

InNetwork InNetwork

func IsIP added in v1.1.8

func IsIP(ip string) bool

IsIP IsIP

func IsLocalAddrIP added in v0.1.42

func IsLocalAddrIP(ip string) bool

IsLocalAddrIP IsLocalAddrIP

func IsLocalIP added in v0.1.42

func IsLocalIP(ip net.IP) bool

IsLocalIP IsLocalIP

func JSONRPC added in v1.4.3

func JSONRPC(rcvr map[string]interface{}, opts ...func(o *JSONRPCOption)) func(c *Context)

func LongToIP added in v1.1.18

func LongToIP(i uint) (string, error)

LongToIP LongToIP

func LongToNetIP added in v1.1.18

func LongToNetIP(i uint) (ip net.IP, err error)

LongToNetIP LongToNetIP

func LongToNetIPv6 added in v1.1.18

func LongToNetIPv6(i *big.Int) (ip net.IP, err error)

LongToNetIPv6 LongToNetIPv6

func MultiplePort added in v1.1.8

func MultiplePort(ports []int, change bool) (int, error)

MultiplePort Check if the multiple port is available, if not, then automatically get an available

func NetIPToLong added in v1.1.18

func NetIPToLong(ip net.IP) (i uint, err error)

NetIPToLong NetIPToLong

func NetIPv6ToLong added in v1.1.18

func NetIPv6ToLong(ip net.IP) (*big.Int, error)

NetIPv6ToLong NetIPv6ToLong

func Port added in v1.1.8

func Port(port int, change bool) (newPort int, err error)

Port GetPort Check if the port is available, if not, then automatically get an available

func RemoteIP

func RemoteIP(r *http.Request) string

RemoteIP Remote IP

func Run

func Run()

Run serve

func SetShutdown added in v1.2.0

func SetShutdown(done func())

SetShutdown Set Shutdown Func

Types

type ApiData added in v0.1.36

type ApiData struct {
	Data interface{} `json:"data"`
	Msg  string      `json:"msg,omitempty"`
	Code int32       `json:"code" example:"200"`
}

ApiData unified return api format

type Context

type Context struct {
	Writer http.ResponseWriter

	Request *http.Request

	Engine *Engine
	Log    *zlog.Logger
	Cache  *zcache.Table
	// contains filtered or unexported fields
}

Context context

func (*Context) Abort

func (c *Context) Abort(code ...int32)

Abort stop executing subsequent handlers

func (*Context) ApiJSON added in v0.1.36

func (c *Context) ApiJSON(code int32, msg string, data interface{})

ApiJSON ApiJSON

func (*Context) Bind added in v0.0.19

func (c *Context) Bind(obj interface{}) (err error)

func (*Context) BindForm added in v1.2.0

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

func (*Context) BindJSON added in v1.2.0

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

func (*Context) BindQuery added in v1.2.0

func (c *Context) BindQuery(obj interface{}) (err error)

func (*Context) BindValid added in v0.1.40

func (c *Context) BindValid(obj interface{}, v map[string]zvalid.Engine) error

func (*Context) Byte added in v0.0.23

func (c *Context) Byte(code int32, value []byte)
func (c *Context) CompletionLink(link string) string

CompletionLink Complete the link and add the current domain name if it is not linked

func (*Context) ContentType added in v0.0.19

func (c *Context) ContentType(contentText ...string) string

ContentType returns the Content-Type header of the request

func (*Context) DefaultFormOrQuery added in v0.0.19

func (c *Context) DefaultFormOrQuery(key string, def string) string

DefaultFormOrQuery Get Form Or Query

func (*Context) DefaultPostForm

func (c *Context) DefaultPostForm(key, def string) string

DefaultPostForm Get Form Or Default

func (*Context) DefaultQuery

func (c *Context) DefaultQuery(key string, def string) string

DefaultQuery Get Query Or Default

func (*Context) File

func (c *Context) File(path string)

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile FormFile

func (*Context) FormFiles added in v1.4.3

func (c *Context) FormFiles(name string) (files []*multipart.FileHeader, err error)

FormFiles Multiple FormFile

func (*Context) GetAllParam

func (c *Context) GetAllParam() ParamsMapType

GetAllParam Get the value of all param in the route

func (*Context) GetAllQuery added in v1.3.1

func (c *Context) GetAllQuery() url.Values

GetAllQuery Get All Queryst

func (*Context) GetAllQueryMaps added in v1.3.1

func (c *Context) GetAllQueryMaps() map[string]string

GetAllQueryMaps Get All Queryst Maps

func (*Context) GetClientIP added in v0.1.20

func (c *Context) GetClientIP() (IP string)

GetClientIP Client IP

func (*Context) GetCookie

func (c *Context) GetCookie(name string) string

GetCookie Get Cookie

func (*Context) GetDataRaw added in v0.0.19

func (c *Context) GetDataRaw() (string, error)

GetDataRaw Get Raw Data

func (*Context) GetHeader

func (c *Context) GetHeader(key string) string

GetHeader Get Header

func (*Context) GetJSON added in v0.0.19

func (c *Context) GetJSON(key string) *zjson.Res

GetJSON Get JSON

func (*Context) GetJSONs added in v0.0.19

func (c *Context) GetJSONs() (json *zjson.Res, err error)

GetJSONs Get JSONs

func (*Context) GetParam

func (c *Context) GetParam(key string) string

GetParam Get the value of the param inside the route

func (*Context) GetPostForm

func (c *Context) GetPostForm(key string) (string, bool)

GetPostForm Get PostForm

func (*Context) GetPostFormAll added in v0.0.19

func (c *Context) GetPostFormAll() (value url.Values)

GetPostFormAll Get PostForm All

func (*Context) GetPostFormArray

func (c *Context) GetPostFormArray(key string) ([]string, bool)

GetPostFormArray Get Post FormArray

func (*Context) GetPostFormMap

func (c *Context) GetPostFormMap(key string) (map[string]string, bool)

GetPostFormMap Get PostForm Map

func (*Context) GetQuery

func (c *Context) GetQuery(key string) (string, bool)

GetQuery Get Query

func (*Context) GetQueryArray

func (c *Context) GetQueryArray(key string) ([]string, bool)

GetQueryArray Get Query Array

func (*Context) GetQueryMap added in v1.2.0

func (c *Context) GetQueryMap(key string) (map[string]string, bool)

GetQueryMap Get Query Map

func (*Context) GetReferer added in v0.1.20

func (c *Context) GetReferer() string

GetReferer request referer

func (*Context) GetUserAgent added in v0.1.20

func (c *Context) GetUserAgent() string

GetUserAgent http request UserAgent

func (*Context) HTML

func (c *Context) HTML(code int32, html string)

HTML export html

func (*Context) Host

func (c *Context) Host(full ...bool) string

Host Get the current Host

func (*Context) Injector added in v1.3.0

func (c *Context) Injector() zdi.Injector

func (*Context) IsAjax added in v0.1.30

func (c *Context) IsAjax() bool

IsAjax IsAjax

func (*Context) IsSSE added in v1.4.2

func (c *Context) IsSSE() bool

IsSSE Is SSE

func (*Context) IsWebsocket

func (c *Context) IsWebsocket() bool

IsWebsocket Is Websocket

func (*Context) JSON

func (c *Context) JSON(code int32, values interface{})

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm MultipartForm

func (*Context) MustValue added in v1.4.3

func (c *Context) MustValue(key string, def ...interface{}) (value interface{})

Value get context sharing data

func (*Context) Next

func (c *Context) Next()

Next Handler

func (*Context) ParseMultipartForm added in v1.3.1

func (c *Context) ParseMultipartForm(maxMultipartMemory ...int64) error

func (*Context) PostFormMap

func (c *Context) PostFormMap(key string) map[string]string

PostFormMap PostForm Map

func (*Context) PrevContent added in v0.0.19

func (c *Context) PrevContent() *PrevData

PrevContent current output content

func (*Context) QueryMap added in v1.2.0

func (c *Context) QueryMap(key string) map[string]string

QueryMap Get Query Map

func (*Context) Redirect

func (c *Context) Redirect(link string, statusCode ...int32)

Redirect Redirect

func (*Context) SaveUploadedFile

func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dist string) error

SaveUploadedFile Save Uploaded File

func (*Context) SetContent deprecated added in v0.1.21

func (c *Context) SetContent(data *PrevData)

Deprecated: You can directly modify the return value of PrevContent()

func (*Context) SetContentType added in v0.0.26

func (c *Context) SetContentType(contentType string) *Context

func (*Context) SetCookie

func (c *Context) SetCookie(name, value string, maxAge ...int)

SetCookie Set Cookie

func (*Context) SetHeader

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

SetHeader Set Header

func (*Context) SetStatus added in v0.0.19

func (c *Context) SetStatus(code int32) *Context

func (*Context) String

func (c *Context) String(code int32, format string, values ...interface{})

func (*Context) Template

func (c *Context) Template(code int32, name string, data interface{}, funcMap ...map[string]interface{})

Template export tpl

func (*Context) Templates added in v0.1.47

func (c *Context) Templates(code int32, templates []string, data interface{}, funcMap ...map[string]interface{})

func (*Context) Valid added in v0.0.20

func (c *Context) Valid(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

Valid Valid from -> query -> parame

func (*Context) ValidForm added in v0.0.20

func (c *Context) ValidForm(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

ValidForm get and verify postform

func (*Context) ValidJSON added in v0.0.20

func (c *Context) ValidJSON(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

ValidJSON get and verify json

func (*Context) ValidParam added in v0.0.20

func (c *Context) ValidParam(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

ValidParam get and verify routing parameters

func (*Context) ValidQuery added in v0.0.20

func (c *Context) ValidQuery(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

ValidQuery get and verify query

func (*Context) ValidRule added in v0.0.20

func (c *Context) ValidRule() zvalid.Engine

func (*Context) Value added in v0.0.19

func (c *Context) Value(key string, def ...interface{}) (value interface{}, ok bool)

Value get context sharing data

func (*Context) WithValue added in v0.0.19

func (c *Context) WithValue(key string, value interface{}) *Context

WithValue context sharing data

type Data added in v0.0.19

type Data map[string]interface{}

Data map string

type Engine

type Engine struct {
	Cache *zcache.Table

	Log *zlog.Logger

	BindTag             string
	BindStructDelimiter string
	BindStructSuffix    string

	MaxMultipartMemory int64

	ShowFavicon bool
	// contains filtered or unexported fields
}

Engine is a simple HTTP route multiplexer that parses a request path

func New

func New(serverName ...string) *Engine

New returns a newly initialized Engine object that implements the Engine

func Server

func Server(serverName ...string) (engine *Engine, ok bool)

Server Server

func (*Engine) AddAddr added in v0.0.19

func (e *Engine) AddAddr(addrString string, tlsConfig ...TlsCfg)

AddAddr AddAddr

func (*Engine) Any

func (e *Engine) Any(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) BindStruct added in v0.1.42

func (e *Engine) BindStruct(prefix string, s interface{}, handle ...Handler) error

BindStruct Bind Struct

func (*Engine) CONNECT added in v0.1.64

func (e *Engine) CONNECT(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) CONNECTAndName added in v0.1.64

func (e *Engine) CONNECTAndName(path string, action Handler, routeName string) *Engine

func (*Engine) Customize added in v0.0.19

func (e *Engine) Customize(method, path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) DELETE

func (e *Engine) DELETE(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) DELETEAndName

func (e *Engine) DELETEAndName(path string, action Handler, routeName string) *Engine

func (*Engine) FindHandle added in v0.0.19

func (e *Engine) FindHandle(rw *Context, req *http.Request, requestURL string, applyMiddleware bool) (not bool)

func (*Engine) GET

func (e *Engine) GET(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) GETAndName

func (e *Engine) GETAndName(path string, action Handler, routeName string) *Engine

func (*Engine) GenerateURL

func (e *Engine) GenerateURL(method string, routeName string, params map[string]string) (string, error)

func (*Engine) GetMode added in v1.3.1

func (e *Engine) GetMode() string

GetMode Get Mode

func (*Engine) GetTrees

func (e *Engine) GetTrees() map[string]*Tree

GetTrees Load Trees

func (*Engine) Group

func (e *Engine) Group(prefix string, groupHandle ...func(e *Engine)) (engine *Engine)

func (*Engine) HEAD

func (e *Engine) HEAD(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) HEADAndName

func (e *Engine) HEADAndName(path string, action Handler, routeName string) *Engine

func (*Engine) Handle

func (e *Engine) Handle(method string, path string, action Handler, moreHandler ...Handler) *Engine

Handle registers new request handlerFn

func (*Engine) HandleNotFound

func (e *Engine) HandleNotFound(c *Context)

func (*Engine) Injector added in v1.3.0

func (e *Engine) Injector() zdi.TypeMapper

Injector Call Injector

func (*Engine) IsDebug

func (e *Engine) IsDebug() bool

IsDebug IsDebug

func (*Engine) LoadHTMLGlob added in v1.1.3

func (e *Engine) LoadHTMLGlob(pattern string)

LoadHTMLGlob Load Glob HTML

func (*Engine) Match

func (e *Engine) Match(requestURL string, path string) bool

Match checks if the request matches the route pattern

func (*Engine) NewContext added in v0.1.34

func (e *Engine) NewContext(w http.ResponseWriter, req *http.Request) *Context

func (*Engine) NotFoundHandler added in v0.0.26

func (e *Engine) NotFoundHandler(handler Handler)

func (*Engine) OPTIONS

func (e *Engine) OPTIONS(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) OPTIONSAndName

func (e *Engine) OPTIONSAndName(path string, action Handler, routeName string) *Engine

func (*Engine) PATCH

func (e *Engine) PATCH(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) PATCHAndName

func (e *Engine) PATCHAndName(path string, action Handler, routeName string) *Engine

func (*Engine) POST

func (e *Engine) POST(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) POSTAndName

func (e *Engine) POSTAndName(path string, action Handler, routeName string) *Engine

func (*Engine) PUT

func (e *Engine) PUT(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) PUTAndName

func (e *Engine) PUTAndName(path string, action Handler, routeName string) *Engine

func (*Engine) PanicHandler deprecated

func (e *Engine) PanicHandler(handler ErrHandlerFunc)

Deprecated: please use znet.Recovery(func(c *Context, err error) {}) PanicHandler is used for handling panics

func (*Engine) PreHandler added in v0.1.53

func (e *Engine) PreHandler(preHandler Handler)

func (*Engine) Restart added in v0.0.22

func (e *Engine) Restart() error

Restart Restart

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Engine) SetAddr

func (e *Engine) SetAddr(addrString string, tlsConfig ...TlsCfg)

SetAddr SetAddr

func (*Engine) SetCustomMethodField

func (e *Engine) SetCustomMethodField(field string)

SetCustomMethodField Set Custom Method Field

func (*Engine) SetHTMLTemplate added in v1.1.10

func (e *Engine) SetHTMLTemplate(t *template.Template)

SetHTMLTemplate Set HTML Template

func (*Engine) SetMode

func (e *Engine) SetMode(value string)

SetMode Setting Server Mode

func (*Engine) SetTemplateFuncMap added in v1.1.3

func (e *Engine) SetTemplateFuncMap(funcMap template.FuncMap)

SetTemplateFuncMap Set Template Func

func (*Engine) SetTimeout

func (e *Engine) SetTimeout(Timeout time.Duration, WriteTimeout ...time.Duration)

SetTimeout set Timeout

func (*Engine) StartUp added in v1.1.15

func (e *Engine) StartUp() []*serverMap

func (*Engine) Static

func (e *Engine) Static(relativePath, root string)

func (*Engine) StaticFS

func (e *Engine) StaticFS(relativePath string, fs http.FileSystem)

func (*Engine) StaticFile

func (e *Engine) StaticFile(relativePath, filepath string)

func (*Engine) TRACE added in v0.1.64

func (e *Engine) TRACE(path string, action Handler, moreHandler ...Handler) *Engine

func (*Engine) TRACEAndName added in v0.1.64

func (e *Engine) TRACEAndName(path string, action Handler, routeName string) *Engine

func (*Engine) Use

func (e *Engine) Use(middleware ...Handler)

type ErrHandlerFunc added in v1.3.0

type ErrHandlerFunc func(c *Context, err error)

ErrHandlerFunc ErrHandlerFunc

type Handler added in v1.3.0

type Handler interface{}

Handler handler func

func Recovery added in v0.1.37

func Recovery(handler ErrHandlerFunc) Handler

Recovery is a middleware that recovers from panics anywhere in the chain

func RewriteErrorHandler added in v1.3.0

func RewriteErrorHandler(handler ErrHandlerFunc) Handler

RewriteErrorHandler rewrite error handler

type HandlerFunc

type HandlerFunc func(c *Context)

HandlerFunc old handler func

type JSONRPCOption added in v1.4.3

type JSONRPCOption struct {
	DisabledHTTP bool
	Debug        bool
}

type MiddlewareFunc

type MiddlewareFunc func(c *Context, fn Handler)

MiddlewareFunc Middleware Func

type MiddlewareType

type MiddlewareType Handler

MiddlewareType is a public type that is used for middleware

type Node

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

Node records any URL params, and executes an end handlerFn.

func NewNode

func NewNode(key string, depth int) *Node

type Parameters

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

Parameters records some parameters

type ParamsMapType

type ParamsMapType map[string]string

ParamsMapType Storage path parameters

type PrevData added in v0.1.21

type PrevData struct {
	Code    *zutil.Int32
	Type    string
	Content []byte
}

type SSE added in v1.4.2

type SSE struct {
	Comment []byte
	// contains filtered or unexported fields
}

func NewSSE added in v1.4.2

func NewSSE(c *Context, opts ...func(lastID string, opts *SSEOption)) *SSE

func (*SSE) Done added in v1.4.2

func (s *SSE) Done() <-chan struct{}

func (*SSE) LastEventID added in v1.4.2

func (s *SSE) LastEventID() string

func (*SSE) Push added in v1.4.2

func (s *SSE) Push()

func (*SSE) Send added in v1.4.2

func (s *SSE) Send(id string, data string, event ...string) error

func (*SSE) SendByte added in v1.4.2

func (s *SSE) SendByte(id string, data []byte, event ...string) error

func (*SSE) Stop added in v1.4.2

func (s *SSE) Stop()

type SSEOption added in v1.4.2

type SSEOption struct {
	RetryTime      int
	HeartbeatsTime time.Duration
}

type TlsCfg added in v0.0.19

type TlsCfg struct {
	HTTPProcessing interface{}
	Config         *tls.Config
	Cert           string
	Key            string
	HTTPAddr       string
}

type Tree

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

Tree records node

func NewTree

func NewTree() *Tree

func (*Tree) Add

func (t *Tree) Add(path string, handle handlerFn, middleware ...handlerFn)

func (*Tree) Find

func (t *Tree) Find(pattern string, isRegex bool) (nodes []*Node)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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