flow

package module
v1.3.9 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2020 License: MIT Imports: 26 Imported by: 2

README

flow

golang web frame as like koajs(洋葱圈模型)

安装

  • go get -u github.com/funswe/flow

示例1

func main() {
	flow.ALL("/hello", func(ctx *flow.Context) {
		ctx.Body("hello,world")
	})
	fmt.Println("启动...")
	log.Fatal(flow.Run())
}

启动程序,在浏览器里访问http://localhost:9505/hello,可以看到浏览器返回hello,world

示例2

func main() {
	flow.GET("/test/:name", func(ctx *flow.Context) {
		fmt.Println("name===", ctx.GetParam("name"))
		ctx.Json(map[string]interface{}{
			"name": ctx.GetParam("name"),
		})
	})
	flow.Use(func(ctx *flow.Context, next flow.Next) {
		fmt.Println("mid1->start,time==", time.Now().UnixNano())
		next()
		fmt.Println("mid1->end,time===", time.Now().UnixNano())
	})
	fmt.Println("启动...")
	log.Fatal(flow.Run())
}

启动程序,在浏览器里访问http://localhost:9505/test/hello,可以看到浏览器返回{"name":"hello"},终端打印

mid1->start,time== 1550045289462400763
name=== hello
mid1->end,time=== 1550045289462472332

示例3

type request struct {
	Age  int    `json:"age,string"`
	Name string `json:"name"`
}

func main() {
	flow.GET("/test/:name", func(ctx *flow.Context) {
       	req := &request{}
       	ctx.Parse(req)
       	ctx.Json(map[string]interface{}{
       		"name": req.Name,
       		"age":  req.Age,
       	})
    })
	fmt.Println("启动...")
	log.Fatal(flow.Run())
}

启动程序,在浏览器里访问http://localhost:9505/test/hello?age=30,可以看到浏览器返回{"age":30,"name":"hello"}

更多例子

模板

使用的HTML模板pongo2

Documentation

Index

Constants

View Source
const (
	HttpMethodGet     = "GET"
	HttpMethodHead    = "HEAD"
	HttpMethodOptions = "OPTIONS"
	HttpMethodPost    = "POST"
	HttpMethodPut     = "PUT"
	HttpMethodPatch   = "PATCH"
	HttpMethodDelete  = "DELETE"
)

定义请求的方法

View Source
const (
	HttpHeaderContentType             = "Content-Type"
	HttpHeaderContentLength           = "Content-Length"
	HttpHeaderTransferEncoding        = "Transfer-Encoding"
	HttpHeaderContentDisposition      = "Content-Disposition"
	HttpHeaderContentTransferEncoding = "Content-Transfer-Encoding"
	HttpHeaderExpires                 = "Expires"
	HttpHeaderCacheControl            = "Cache-Control"
	HttpHeaderEtag                    = "Etag"
	HttpHeaderXForwardedHost          = "X-Forwarded-Host"
	HttpHeaderXForwardedProto         = "X-Forwarded-Proto"
	HttpHeaderIfModifiedSince         = "If-Modified-Since"
	HttpHeaderIfNoneMatch             = "If-None-Match"
	HttpHeaderLastModified            = "Last-Modified"
	HttpHeaderXContentTypeOptions     = "X-Content-Type-Options"
	HttpHeaderXPoweredBy              = "X-Powered-By"
	HttpHeaderCorsOrigin              = "Access-Control-Allow-Origin"
	HttpHeaderCorsMethods             = "Access-Control-Allow-Methods"
	HttpHeaderCorsHeaders             = "Access-Control-Allow-Headers"
)

定义http头

View Source
const Nil = NotExistError("flow-redis: key not exist")

Variables

This section is empty.

Functions

func ALL added in v1.0.3

func ALL(path string, handler Handler)

func DELETE added in v1.0.3

func DELETE(path string, handler Handler)

func GET added in v1.0.3

func GET(path string, handler Handler)
func HEAD(path string, handler Handler)

func OPTIONS added in v1.0.3

func OPTIONS(path string, handler Handler)

func PATCH added in v1.0.3

func PATCH(path string, handler Handler)

func POST added in v1.0.3

func POST(path string, handler Handler)

func PUT added in v1.0.3

func PUT(path string, handler Handler)

func Run added in v1.0.3

func Run() error

启动服务

func SetCorsConfig added in v1.3.3

func SetCorsConfig(corsConfig *CorsConfig)

设置跨域配置

func SetCurlConfig added in v1.3.3

func SetCurlConfig(curlConfig *CurlConfig)

设置httpclient配置

func SetLoggerConfig added in v1.2.0

func SetLoggerConfig(loggerConfig *LoggerConfig)

设置日志配置

func SetNotFoundHandle added in v1.0.3

func SetNotFoundHandle(nfh NotFoundHandle)

func SetOrmConfig added in v1.2.0

func SetOrmConfig(ormConfig *OrmConfig)

设置数据库配置

func SetPanicHandler added in v1.0.3

func SetPanicHandler(ph PanicHandler)

func SetRedisConfig added in v1.3.3

func SetRedisConfig(redisConfig *RedisConfig)

设置redis配置

func SetServerConfig added in v1.2.0

func SetServerConfig(serverConfig *ServerConfig)

设置服务配置

func Use added in v1.0.3

func Use(m Middleware)

添加中间件

Types

type Application

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

定义服务的APP

type Context

type Context struct {
	Logger *log.Logger // 上下文的logger对象,打印日志会自动带上请求的相关参数

	Orm   *Orm         // 数据库操作对象,引用app的orm对象
	Redis *RedisClient // redis操作对象,引用app的redis对象
	Curl  *Curl        // httpclient操作对象,引用app的curl对象
	// contains filtered or unexported fields
}

定义请求上下文对象

func (*Context) Body

func (c *Context) Body(body string)

返回文本数据

func (*Context) Download

func (c *Context) Download(filePath string)

下载文件

func (*Context) GetApp added in v1.2.0

func (c *Context) GetApp() *Application

获取app对象

func (*Context) GetHeader

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

获取请求的头信息

func (*Context) GetHeaders

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

获取请求的所有头信息

func (*Context) GetHost

func (c *Context) GetHost() string

获取请求的HOST信息

func (*Context) GetHostname

func (c *Context) GetHostname() string

获取请求的hostname

func (*Context) GetHref

func (c *Context) GetHref() string

获取请求的完整链接

func (*Context) GetLength

func (c *Context) GetLength() int

获取请求的内容长度

func (*Context) GetMethod

func (c *Context) GetMethod() string

获取请求的方法,如GET,POST

func (*Context) GetOrigin

func (c *Context) GetOrigin() string

获取请求的地址

func (*Context) GetParam

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

获取请求的参数

func (*Context) GetParamDefault

func (c *Context) GetParamDefault(key, defaultValue string) (value string)

获取请求的参数,可以设置默认值

func (*Context) GetProtocol

func (c *Context) GetProtocol() string

获取请求的协议,http or https

func (*Context) GetQuery

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

获取请求的query参数,map格式

func (*Context) GetQuerystring

func (c *Context) GetQuerystring() string

获取请求的querystring

func (*Context) GetStatusCode added in v1.0.8

func (c *Context) GetStatusCode() int

获取返回的http状态码

func (*Context) GetUri

func (c *Context) GetUri() string

获取请求的URI

func (*Context) GetUserAgent added in v1.0.2

func (c *Context) GetUserAgent() string

获取请求的ua

func (*Context) IsSecure

func (c *Context) IsSecure() bool

判断是不是https请求

func (*Context) Json added in v1.0.2

func (c *Context) Json(data map[string]interface{})

返回json数据

func (*Context) Parse added in v1.0.2

func (c *Context) Parse(object interface{}) error

解析请求的参数,将参数赋值到给定的对象里

func (*Context) Redirect

func (c *Context) Redirect(url string, code int)

设置返回的重定向地址

func (*Context) Render added in v1.0.2

func (c *Context) Render(tmpFile string, data map[string]interface{})

返回服务端渲染文本信息

func (*Context) SetHeader

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

设置返回的头信息

func (*Context) SetLength

func (c *Context) SetLength(length int) *Context

设置返回体的长度

func (*Context) SetStatus

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

设置返回的http状态码

type CorsConfig added in v1.3.3

type CorsConfig struct {
	Enable         bool // 是否开始跨域支持
	AllowOrigin    string
	AllowedHeaders string
	AllowedMethods string
}

定义跨域配置

type Curl added in v1.3.3

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

定义httpclient对象

func (*Curl) Get added in v1.3.3

func (c *Curl) Get(url string, data interface{}, headers map[string]string) (CurlResult, error)

func (*Curl) Post added in v1.3.3

func (c *Curl) Post(url string, data interface{}, headers map[string]string) (CurlResult, error)

type CurlConfig added in v1.3.3

type CurlConfig struct {
	Timeout time.Duration     // 请求的超时时间,单位秒
	Headers map[string]string // 统一请求的头信息
}

定义httpclient配置

type CurlResult added in v1.3.3

type CurlResult string

定义返回的结果

func (CurlResult) Parse added in v1.3.3

func (cr CurlResult) Parse(v interface{}) error

将返回的结果定义到给定的对象里

func (CurlResult) Raw added in v1.3.3

func (cr CurlResult) Raw(v interface{}) string

返回原始的请求字符串结果数据

type Handler

type Handler func(ctx *Context)

定义路由处理器

type LoggerConfig added in v1.2.0

type LoggerConfig struct {
	LoggerLevel string
	LoggerPath  string
}

定义日志配置

type Middleware

type Middleware func(ctx *Context, next Next)

定义中间件接口

type Next

type Next func()

type NotExistError added in v1.3.3

type NotExistError string

定义redis键不存在错误对象

func (NotExistError) Error added in v1.3.3

func (e NotExistError) Error() string

func (NotExistError) NotExistError added in v1.3.3

func (NotExistError) NotExistError()

type NotFoundHandle added in v1.0.2

type NotFoundHandle func(w http.ResponseWriter, r *http.Request)

func (NotFoundHandle) ServeHTTP added in v1.0.2

func (f NotFoundHandle) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Orm added in v1.2.0

type Orm struct {
	Op       *OrmOp       // 数据库查询条件操作符对象
	JoinType *OrmJoinType // 数据库JOIN表类型对象
	// contains filtered or unexported fields
}

定义数据库操作对象

func (*Orm) Count added in v1.2.6

func (orm *Orm) Count(count *int64, fromTable *OrmFromTable, conditions []*OrmWhere) error

返回查询的总条数

func (*Orm) DB added in v1.2.6

func (orm *Orm) DB() *gorm.DB

返回grom db对象,用于原生查询使用

func (*Orm) Query added in v1.2.6

func (orm *Orm) Query(dest interface{}, fields interface{}, fromTable *OrmFromTable, conditions []*OrmWhere, orderBy []*OrmOrderBy, limit *OrmLimit, groupBy *OrmGroupBy) error

数据库查询方法

type OrmColumn added in v1.2.6

type OrmColumn struct {
	Table  string // 表名
	Column string // 列名
	Alias  string // 别名
}

定义数据库表列结构

type OrmConfig added in v1.2.0

type OrmConfig struct {
	Enable   bool
	UserName string
	Password string
	DbName   string
	Host     string
	Port     int
	Pool     *OrmPool
}

定义数据库配置

type OrmFromTable added in v1.2.6

type OrmFromTable struct {
	Table string     // 表名
	Alias string     // 别名
	Joins []*OrmJoin // JOIN表集合
}

定义数据库查询表结构

type OrmGroupBy added in v1.2.6

type OrmGroupBy struct {
	Columns []*OrmColumn // 列集合
	Having  []*OrmWhere  // having条件集合
}

定义数据库GROUP BY结构

type OrmJoin added in v1.2.6

type OrmJoin struct {
	Type  string      // JOIN类型
	Table string      // 表名
	Alias string      // 别名
	ON    []*OrmWhere // JOIN条件
}

定义数据库JOIN表结构

type OrmJoinType added in v1.2.7

type OrmJoinType struct {
	CrossJoin string
	InnerJoin string
	LeftJoin  string
	RightJoin string
}

定义数据库JOIN表类型

type OrmLimit added in v1.2.6

type OrmLimit struct {
	Limit  int
	Offset int
}

定义数据库LIMIT结构

type OrmOp added in v1.2.6

type OrmOp struct {
	Eq   string
	Gt   string
	Gte  string
	Lt   string
	Lte  string
	IN   string
	Like string
	Or   string
}

定义数据库查询条件操作符

type OrmOrderBy added in v1.2.6

type OrmOrderBy struct {
	Column *OrmColumn // 表列
	Desc   bool       // 是否是倒序
}

定义数据库ORDER BY结构

type OrmPool added in v1.2.0

type OrmPool struct {
	MaxIdle         int
	MaxOpen         int
	ConnMaxLifeTime int64
	ConnMaxIdleTime int64
}

定义数据库连接池配置

type OrmWhere added in v1.2.6

type OrmWhere struct {
	Column *OrmColumn  // 表列
	Opt    string      // 操作符
	Value  interface{} //条件的值
}

定义数据库条件结构

type PanicHandler added in v1.0.2

type PanicHandler func(http.ResponseWriter, *http.Request, interface{})

type RedisClient added in v1.3.3

type RedisClient struct {
	NotExist NotExistError
	// contains filtered or unexported fields
}

定义redis操作对象

func (*RedisClient) Get added in v1.3.3

func (rd *RedisClient) Get(key string, v interface{}) error

将值赋值给指定的结构对象

func (*RedisClient) GetRaw added in v1.3.3

func (rd *RedisClient) GetRaw(key string) (string, error)

获取原始的字符串值

func (*RedisClient) Set added in v1.3.3

func (rd *RedisClient) Set(key string, value interface{}, expiration time.Duration) error

设置结构体或者map的值

func (*RedisClient) SetRaw added in v1.3.3

func (rd *RedisClient) SetRaw(key string, value string, expiration time.Duration) error

设置原始的字符串值

type RedisConfig added in v1.3.3

type RedisConfig struct {
	Enable   bool
	Password string
	DbNum    int
	Host     string
	Port     int
}

定义redis配置结构

type ServerConfig added in v1.2.0

type ServerConfig struct {
	AppName    string // 应用名称
	Proxy      bool   // 是否是代理模式
	Host       string // 服务启动地址
	Port       int    // 服务端口
	ViewPath   string // 服务端渲染视图文件路径,使用pongo2模板
	StaticPath string // 服务器静态资源路径
}

定义服务配置

Directories

Path Synopsis
utils

Jump to

Keyboard shortcuts

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