TigoWeb

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2019 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package TigoWeb 框架的基本功能包,此包包含了搭建服务的基础功能

Package TigoWeb Copyright 2018 The Tigo Authors. All rights reserved.

Package TigoWeb Copyright 2018 The Tigo Authors. All rights reserved.

Package TigoWeb Copyright 2018 The Tigo Authors. All rights reserved.

Index

Constants

View Source
const Version = "1.0.9"

Variables

View Source
var MethodMapping = map[string]string{
	"get":     "Get",
	"head":    "Head",
	"post":    "Post",
	"put":     "Put",
	"delete":  "Delete",
	"connect": "Connect",
	"options": "Options",
	"trace":   "Trace",
	"GET":     "Get",
	"HEAD":    "Head",
	"POST":    "Post",
	"PUT":     "Put",
	"DELETE":  "Delete",
	"CONNECT": "Connect",
	"OPTIONS": "Options",
	"TRACE":   "Trace",
}

MethodMapping http请求方式的一个映射

Functions

func Decrypt

func Decrypt(src []byte, key []byte) []byte

Decrypt 方法会先对原始数据进行base64解码,然后根据key进行解密, 解密失败则返回空

  • 此处以后会进行异常处理方面的优化

func Encrypt

func Encrypt(src []byte, key []byte) string

Encrypt 方法用来根据key对原始数据进行加密,并将加密结果进行base64编码, 加密失败则返回空

  • 此处以后会进行异常处理方面的优化

func HttpContextLogMiddleware added in v1.0.5

func HttpContextLogMiddleware(next http.HandlerFunc) http.HandlerFunc

HttpContextLogMiddleware 记录一个http请求响应时间的中间件

func InitGlobalConfig

func InitGlobalConfig(configPath string)

InitGlobalConfig 方法用来初始化全局变量

func InitGlobalConfigWithObj added in v1.0.8

func InitGlobalConfigWithObj(config GlobalConfig)

InitGlobalConfigWithObj 可使用TigoWeb.GlobalConfig的实例进行初始化全局变量

func InternalServerErrorMiddleware added in v1.0.4

func InternalServerErrorMiddleware(next http.HandlerFunc) http.HandlerFunc

InternalServerErrorMiddleware 用来处理控制层出现的异常的中间件

Types

type Application

type Application struct {
	IPAddress  string                 // IP地址
	Port       int                    // 端口
	UrlPattern map[string]interface{} // url路由配置
	UrlRouters []Router               // url路由配置
	ConfigPath string                 // 全局配置
}

Application web容器

func (*Application) Listen added in v1.0.8

func (application *Application) Listen(port int)

Listen 端口监听

func (*Application) MountFileServer added in v1.0.9

func (application *Application) MountFileServer(dir string, uris ...string)

MountFileServer 挂载文件服务

  • dir 本地文件地址
  • uris 需要挂载的URI列表

func (*Application) Run

func (application *Application) Run()

Run 服务启动函数

type BaseHandler

type BaseHandler struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	JsonParams     map[string]interface{}
	// contains filtered or unexported fields
}

BaseHandler 是Handler的基础类,开发者开发的handler继承此类

func (*BaseHandler) BeforeRequest added in v1.0.2

func (baseHandler *BaseHandler) BeforeRequest()

BeforeRequest 在每次响应HTTP请求之前执行此函数

func (*BaseHandler) CheckFormBinding added in v1.0.2

func (baseHandler *BaseHandler) CheckFormBinding(obj interface{}) error

CheckFormBinding 检查提交的form是否符合要求

func (*BaseHandler) CheckJsonBinding added in v1.0.1

func (baseHandler *BaseHandler) CheckJsonBinding(obj interface{}) error

CheckJsonBinding 检查提交的json是否符合要求

func (*BaseHandler) CheckParamBinding added in v1.0.2

func (baseHandler *BaseHandler) CheckParamBinding(obj interface{}) error

CheckParamBinding 检查提交的参数是否符合要求

func (*BaseHandler) CheckUrlParamBinding added in v1.0.6

func (baseHandler *BaseHandler) CheckUrlParamBinding(obj interface{}) error

CheckUrlParamBinding 检查url上传递的参数是否符合要求

func (*BaseHandler) ClearAllCookie

func (baseHandler *BaseHandler) ClearAllCookie()

ClearAllCookie 清除当前path下所有的cookie

func (*BaseHandler) ClearCookie

func (baseHandler *BaseHandler) ClearCookie(name string)

ClearCookie 清除当前path下的指定的cookie

func (*BaseHandler) Connect

func (baseHandler *BaseHandler) Connect()

Connect 方法

func (*BaseHandler) Delete

func (baseHandler *BaseHandler) Delete()

Delete 方法

func (*BaseHandler) DumpHttpRequestMsg

func (baseHandler *BaseHandler) DumpHttpRequestMsg(logLevel int)

DumpHttpRequestMsg 获取http请求报文,根据logLevel值进行不同的输出

  • 1: 将http报文输出到trace级别日志中
  • 2: 将http报文输出到info级别日志中
  • 3: 将http报文输出到warning级别日志中
  • 4: 将http报文输出到error级别日志中
  • others: 将http报文输出到控制台

func (*BaseHandler) Get

func (baseHandler *BaseHandler) Get()

Get 方法

func (*BaseHandler) GetBody added in v1.0.1

func (baseHandler *BaseHandler) GetBody() []byte

GetBody 获取HTTP报文体

func (*BaseHandler) GetCookie

func (baseHandler *BaseHandler) GetCookie(name string) (value string)

GetCookie 获取cookie值,如果获取失败则返回空字符串

func (*BaseHandler) GetCookieObject

func (baseHandler *BaseHandler) GetCookieObject(name ...string) (Cookie, error)

GetCookieObject 获取cookie对象,多参数输入,参数如下:

  • 无参数:默认cookieName为空字符串
  • 一个参数:传入的参数为cookieName
  • 多个参数:传入的第一个参数为cookieName,第二个参数为加密/解密cookie所用的Key,此时认为cookie是需要进行加密/解密处理的

func (*BaseHandler) GetCtxVal

func (baseHandler *BaseHandler) GetCtxVal(key string) interface{}

GetCtxVal 从上下文获取值

func (*BaseHandler) GetHeader

func (baseHandler *BaseHandler) GetHeader(name string) (value string)

GetHeader 获取header

func (*BaseHandler) GetJsonValue

func (baseHandler *BaseHandler) GetJsonValue(key string) interface{}

GetJsonValue 根据key获取对应的参数值,解析json数据,返回对应的value

func (*BaseHandler) GetParameter

func (baseHandler *BaseHandler) GetParameter(key string) (value *ReqParams)

GetParameter 根据key获取对应的参数值

  • 如果Content-Type是application/json,则直接从http的body中解析出key对应的value
  • 否则,根据key直接获取value

func (*BaseHandler) GetSecureCookie

func (baseHandler *BaseHandler) GetSecureCookie(name string, key ...string) (value string)

GetSecureCookie 获取加密cookie值,如果获取失败则返回空

func (*BaseHandler) Head

func (baseHandler *BaseHandler) Head()

Head 方法

func (*BaseHandler) InitHandler

func (baseHandler *BaseHandler) InitHandler(responseWriter http.ResponseWriter, request *http.Request)

InitHandler 初始化Handler的方法

func (*BaseHandler) Options

func (baseHandler *BaseHandler) Options()

Options 方法

func (*BaseHandler) PassJson

func (baseHandler *BaseHandler) PassJson()

PassJson 用来解析json中的值

func (*BaseHandler) Post

func (baseHandler *BaseHandler) Post()

Post 方法

func (*BaseHandler) Put

func (baseHandler *BaseHandler) Put()

Put 方法

func (*BaseHandler) Redirect

func (baseHandler *BaseHandler) Redirect(url string, expire ...time.Time)

Redirect 向客户端暂时重定向一个地址

func (*BaseHandler) RedirectPermanently

func (baseHandler *BaseHandler) RedirectPermanently(url string)

RedirectPermanently 向客户端永久重定向一个地址

func (*BaseHandler) Render

func (baseHandler *BaseHandler) Render(data interface{}, templates ...string)

Render 渲染模板,返回数据 参数解析如下:

  • data:表示传入的待渲染的数据
  • templates:表示模板文件的路径,接受多个模板文件

func (*BaseHandler) Response

func (baseHandler *BaseHandler) Response(result ...interface{})

Response 向客户端响应一个结果

func (*BaseHandler) ResponseAsHtml

func (baseHandler *BaseHandler) ResponseAsHtml(result string, charset ...string)

ResponseAsHtml 向客户端响应一个html结果,默认字符集为utf-8

func (*BaseHandler) ResponseAsJson

func (baseHandler *BaseHandler) ResponseAsJson(response interface{}, charset ...string)

ResponseAsJson 向客户端响应一个Json结果,默认字符集为utf-8

func (*BaseHandler) ResponseAsText

func (baseHandler *BaseHandler) ResponseAsText(result string)

ResponseAsText 向客户端响应一个Text结果

func (*BaseHandler) ResponseFmt added in v1.0.4

func (baseHandler *BaseHandler) ResponseFmt(format string, values ...interface{})

ResponseFmt 向客户端响应一个字符串,支持format格式化字符串

func (*BaseHandler) ServerError added in v1.0.4

func (baseHandler *BaseHandler) ServerError(err error)

ServerError 将服务器端发生的错误返回给客户端

func (*BaseHandler) SetAdvancedCookie added in v1.0.9

func (baseHandler *BaseHandler) SetAdvancedCookie(name string, value string, attrs ...string)

SetAdvancedCookie 设置cookie

  • name cookie的名称
  • value cookie的value
  • attrs cookie的其他属性值,示例如下:
  • "path={{string}}" 设置cookie的有效作用地址
  • "domain={{string}}" 设置cookie的作用域
  • "raw={{string}}" 设置cookie的raw值
  • "maxAge={{int}}" 设置cookie的MaxAge,表示未指定“Max-Age”属性,表示现在删除cookie,相当于'Max-Age:0',表示Max-Age属性存在并以秒为单位给出
  • "expires={{int}}" 设置cookie的过期时间,按秒计算
  • "secure={{bool}}" 设置cookie是否只限于加密传输
  • "httpOnly={{bool}}" 设置cookie是否只限于http/https传输
  • "isSecurity={{bool}}" 设置cookie是否要进行加密

func (*BaseHandler) SetCookie

func (baseHandler *BaseHandler) SetCookie(name string, value string)

SetCookie 设置cookie

func (*BaseHandler) SetCookieObject

func (baseHandler *BaseHandler) SetCookieObject(cookie Cookie)

SetCookieObject 设置高级cookie选项

func (*BaseHandler) SetCtxVal

func (baseHandler *BaseHandler) SetCtxVal(key string, val interface{})

SetCtxVal 在上下文中设置值

func (*BaseHandler) SetHeader

func (baseHandler *BaseHandler) SetHeader(name string, value string)

SetHeader 设置header

func (*BaseHandler) SetSecureCookie

func (baseHandler *BaseHandler) SetSecureCookie(name string, value string, key ...string)

SetSecureCookie 设置加密cookie

func (*BaseHandler) TeardownRequest added in v1.0.2

func (baseHandler *BaseHandler) TeardownRequest()

TeardownRequest 在每次响应HTTP请求之后执行此函数

func (*BaseHandler) ToJson

func (baseHandler *BaseHandler) ToJson(response interface{}) (result string)

ToJson 将对象转化为Json字符串,转换失败则返回空字符串。 传入参数Response为一个interface,必须有成员函数Print。

func (*BaseHandler) Trace

func (baseHandler *BaseHandler) Trace()

Trace 方法

type BaseResponse

type BaseResponse struct {
}

BaseResponse 定义BaseResponse类,其他Json数据类继承此类,用于BaseHandler.ResponseAsJson的参数。

func (*BaseResponse) Print

func (baseResponse *BaseResponse) Print()

Print 打印Json数据

func (*BaseResponse) ToJson

func (baseResponse *BaseResponse) ToJson() string

ToJson 序列化为Json字符串

type Cookie struct {
	Name  string
	Value string

	IsSecurity  bool   // 是否对cookie值进行加密
	SecurityKey string // 加密cookie用到的key

	Path       string    // 可选
	Domain     string    // 可选
	Expires    time.Time // 可选
	RawExpires string    // 只有在读取Cookie时有效

	// MaxAge=0 表示未指定“Max-Age”属性
	// MaxAge<0 表示现在删除cookie,相当于'Max-Age:0'
	// MaxAge>0 表示Max-Age属性存在并以秒为单位给出
	MaxAge   int
	Secure   bool
	HttpOnly bool
	Raw      string
	Unparsed []string // 原始文本中未解析的属性值
}

Cookie 是自定义Cookie结构体,可参看http.Cookie

func (*Cookie) ConvertFromHttpCookie

func (cookie *Cookie) ConvertFromHttpCookie(httpCookie http.Cookie)

ConvertFromHttpCookie 将http/Cookie转换为Cookie

func (*Cookie) GetCookieDecodeValue

func (cookie *Cookie) GetCookieDecodeValue() (result string)

GetCookieDecodeValue 获取cookie解密值

  • IsSecurity如果设置为false,则返回原始值
  • IsSecurity如果设置为true,则返回加密后的值

如果解密失败,则抛出异常

func (*Cookie) GetCookieEncodeValue

func (cookie *Cookie) GetCookieEncodeValue() (result string)

GetCookieEncodeValue 获取cookie加密值

  • IsSecurity如果设置为false,则返回原始值
  • IsSecurity如果设置为true,则返回加密后的值

如果加密失败,则抛出异常

func (*Cookie) SetSecurityKey

func (cookie *Cookie) SetSecurityKey(key string)

SetSecurityKey 为Cookie设置SecurityKey

func (*Cookie) ToHttpCookie

func (cookie *Cookie) ToHttpCookie() http.Cookie

ToHttpCookie 转换为http/Cookie对象

type GlobalConfig

type GlobalConfig struct {
	IP       string          `json:"ip"`       // IP地址
	Port     int             `json:"port"`     // 端口
	Cert     string          `json:"cert"`     // https证书路径
	CertKey  string          `json:"cert_key"` // https密钥路径
	Cookie   string          `json:"cookie"`   // cookie加密解密的密钥
	Template string          `json:"template"` // 模板文件所在文件夹的路径
	Log      logger.LogLevel `json:"log"`      // log相关属性配置
}

GlobalConfig 全局配置对象

func (*GlobalConfig) Init

func (globalConfig *GlobalConfig) Init(configPath string)

Init 根据配置文件初始化全局配置变量

type HttpResponseWriter added in v1.0.5

type HttpResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

HttpResponseWriter Http响应写入器,用于在中间件中修改http响应报文

func (*HttpResponseWriter) GetStatus added in v1.0.5

func (httpResponseWriter *HttpResponseWriter) GetStatus() int

GetStatus 获取Http状态码

func (*HttpResponseWriter) WriteHeader added in v1.0.5

func (httpResponseWriter *HttpResponseWriter) WriteHeader(code int)

WriteHeader 设置Http状态码

type Middleware added in v1.0.3

type Middleware func(next http.HandlerFunc) http.HandlerFunc

Middleware http中间件

type ReqParams

type ReqParams struct {
	Value interface{}
}

ReqParams 请求参数结构体

func (*ReqParams) To

func (jsonParam *ReqParams) To(result interface{})

To 将json中的参数值转换为目标对象

func (*ReqParams) ToBool

func (jsonParam *ReqParams) ToBool(defaultValue ...bool) bool

ToBool 将json中的参数值转换为bool

func (*ReqParams) ToFloat64

func (jsonParam *ReqParams) ToFloat64() float64

ToFloat64 将json中解析出的参数格式化为float64类型,失败则返回0

func (*ReqParams) ToInt64

func (jsonParam *ReqParams) ToInt64() int64

ToInt64 将json中解析出来的参数格式化为int64类型,失败则返回0

func (*ReqParams) ToString

func (jsonParam *ReqParams) ToString() string

ToString 将json中解析出的参数格式化为string类型,失败则返回空字符串

type Response

type Response interface {
	Print()
}

Response 响应给客户端的interface,用户自定义实现

type Router added in v1.0.3

type Router struct {
	Url        string
	Handler    interface{}
	Middleware []Middleware
}

Router 路由对象

type UrlPattern

type UrlPattern struct {
	UrlMapping map[string]interface{}
	UrlRouters []Router
}

UrlPattern 是URL路由,此处存储URL映射。

func (*UrlPattern) AppendRouterPattern added in v1.0.3

func (urlPattern *UrlPattern) AppendRouterPattern(router Router, v interface {
	Handle(http.ResponseWriter, *http.Request)
})

AppendRouterPattern 向http服务挂载单个Router,Router中配置有url对应的handler以及对应的中间件

func (*UrlPattern) AppendUrlPattern

func (urlPattern *UrlPattern) AppendUrlPattern(uri string, v interface {
	Handle(http.ResponseWriter, *http.Request)
})

AppendUrlPattern 向http服务挂载单个handler,注意:

  • handler必须有一个Handle(http.ResponseWriter, *http.Request)函数

func (*UrlPattern) Init

func (urlPattern *UrlPattern) Init()

Init 初始化url映射,遍历UrlMapping,将handler与对应的URL依次挂载到http服务上

type UrlPatternMidWare

type UrlPatternMidWare struct {
	Handler interface{}
	// contains filtered or unexported fields
}

UrlPatternMidWare 是URL路由中间件

func (UrlPatternMidWare) Handle

func (urlPatternMidWare UrlPatternMidWare) Handle(responseWriter http.ResponseWriter, request *http.Request)

Handle 封装HTTP请求的中间件,主要有以下功能:

  • 1、根据反射找到挂载的handler;
  • 2、调用handler的InitHandler方法;
  • 3、进行HTTP请求预处理,包括判断请求方式是否合法等;
  • 4、调用handler中的功能方法;
  • 5、进行HTTP请求结束处理。

Jump to

Keyboard shortcuts

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