znet

package
v1.1.13 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2021 License: MIT Imports: 35 Imported by: 24

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 (
	MIMEJSON              = "application/json"
	MIMEPlain             = "text/plain"
	MIMEPOSTForm          = "application/x-www-form-urlencoded"
	MIMEMultipartPOSTForm = "multipart/form-data"
)

Content-Type MIME of the most common data formats

View Source
const (

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

Variables

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__")
	// Shutdown Done executed after shutting down the server
	ShutdownDone func()
	// CloseHotRestart
	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 IP2Long

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

IP2Long IP2Long

func IPString2Long

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

IPString2Long IPString2Long

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 Long2IP

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

Long2IP Long2IP

func Long2IPString

func Long2IPString(i uint) (IP string, err error)

Long2IPString Long2IPString

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 Port added in v1.1.8

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

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

func RemoteIP

func RemoteIP(r *http.Request) string

RemoteIP RemoteIP

func Run

func Run()

Run run serve

Types

type ApiData added in v0.1.36

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

ApiData unified return api format

type Context

type Context struct {
	Writer  http.ResponseWriter
	Request *http.Request
	Engine  *Engine
	Log     *zlog.Logger
	Cache   *zcache.Table
	sync.RWMutex
	// contains filtered or unexported fields
}

Context context

func (*Context) Abort

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

Abort Abort

func (*Context) ApiJSON added in v0.1.36

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

ApiJSON ApiJSON

func (*Context) Bind added in v0.0.19

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

func (*Context) BindValid added in v0.1.40

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

func (*Context) Byte added in v0.0.23

func (c *Context) Byte(code int, 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) GetAllParam

func (c *Context) GetAllParam() ParamsMapType

GetAllParam Get the value of all param in the route

func (*Context) GetAllQueryst

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

GetAllQueryst Get All Queryst

func (*Context) GetAllQuerystMaps added in v0.1.40

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

GetAllQuerystMaps 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, err error)

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) 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 int, html string)

HTML export html

func (*Context) Host

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

Host Get the current Host

func (*Context) IsAjax added in v0.1.30

func (c *Context) IsAjax() bool

IsAjax IsAjax

func (*Context) IsWebsocket

func (c *Context) IsWebsocket() bool

IsWebsocket Is Websocket

func (*Context) JSON

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

func (*Context) MultipartForm

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

MultipartForm MultipartForm

func (*Context) Next

func (c *Context) Next() (next HandlerFunc)

Next Next Handler

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

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

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 int) *Context

func (*Context) String

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

func (*Context) Template

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

Template export tpl

func (*Context) Templates added in v0.1.47

func (c *Context) Templates(code int, 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 {
	// Log Log
	Log   *zlog.Logger
	Cache *zcache.Table

	ShowFavicon        bool
	MaxMultipartMemory int64
	BindTag            string

	BindStructDelimiter string
	BindStructSuffix    string
	// 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, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) BindStruct added in v0.1.42

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

BindStruct Bind Struct

func (*Engine) CONNECT added in v0.1.64

func (e *Engine) CONNECT(path string, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) CONNECTAndName added in v0.1.64

func (e *Engine) CONNECTAndName(path string, handle HandlerFunc, routeName string)

func (*Engine) Customize added in v0.0.19

func (e *Engine) Customize(method, path string, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) DELETE

func (e *Engine) DELETE(path string, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) DELETEAndName

func (e *Engine) DELETEAndName(path string, handle HandlerFunc, routeName string)

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, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) GETAndName

func (e *Engine) GETAndName(path string, handle HandlerFunc, routeName string)

func (*Engine) GenerateURL

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

func (*Engine) GetMiddleware

func (e *Engine) GetMiddleware() []HandlerFunc

GetMiddleware GetMiddleware

func (*Engine) GetPanicHandler added in v0.1.37

func (e *Engine) GetPanicHandler() PanicFunc

func (*Engine) GetTrees

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

GetTrees Get 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, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) HEADAndName

func (e *Engine) HEADAndName(path string, handle HandlerFunc, routeName string)

func (*Engine) Handle

func (e *Engine) Handle(method string, path string, handle HandlerFunc, moreHandler ...HandlerFunc)

Handle registers new request handler

func (*Engine) HandleNotFound

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

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

func (*Engine) OPTIONS

func (e *Engine) OPTIONS(path string, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) OPTIONSAndName

func (e *Engine) OPTIONSAndName(path string, handle HandlerFunc, routeName string)

func (*Engine) PATCH

func (e *Engine) PATCH(path string, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) PATCHAndName

func (e *Engine) PATCHAndName(path string, handle HandlerFunc, routeName string)

func (*Engine) POST

func (e *Engine) POST(path string, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) POSTAndName

func (e *Engine) POSTAndName(path string, handle HandlerFunc, routeName string)

func (*Engine) PUT

func (e *Engine) PUT(path string, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) PUTAndName

func (e *Engine) PUTAndName(path string, handle HandlerFunc, routeName string)

func (*Engine) PanicHandler

func (e *Engine) PanicHandler(handler PanicFunc)

func (*Engine) PreHandler added in v0.1.53

func (e *Engine) PreHandler(preHandler func(context *Context) (stop bool))

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 SetCustomMethodField

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 setTimeout

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, handle HandlerFunc, moreHandler ...HandlerFunc)

func (*Engine) TRACEAndName added in v0.1.64

func (e *Engine) TRACEAndName(path string, handle HandlerFunc, routeName string)

func (*Engine) Use

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

type HandlerFunc

type HandlerFunc func(c *Context)

HandlerFunc HandlerFunc

func Recovery added in v0.1.37

func Recovery(r *Engine, handler PanicFunc) HandlerFunc

Recovery Recovery

type MiddlewareFunc

type MiddlewareFunc func(c *Context, fn HandlerFunc)

MiddlewareFunc MiddlewareFunc

type MiddlewareType

type MiddlewareType HandlerFunc

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

func NewNode

func NewNode(key string, depth int) *Node

type PanicFunc

type PanicFunc func(c *Context, err error)

PanicFunc PanicFunc

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    int
	Type    string
	Content []byte
}

type TlsCfg added in v0.0.19

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

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(pattern string, handle HandlerFunc, middleware ...HandlerFunc)

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