gow

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2020 License: Apache-2.0 Imports: 26 Imported by: 0

README

gow

gow 是一个基于gin框架思想和beego框架中html模板处理机制,封装的一个go web框架。可用于开发Web API和Web网站项目。

项目地址:

https://github.com/gkzy/gow

官网地址:

https://gow.22v.net

1. 快速开始
mkdir hello
cd hello
go mod init
go get github.com/gkzy/gow
1.1 创建 main.go
package main

import (
    "github.com/gkzy/gow"
)

func main() {
    r := gow.Default()

    r.GET("/", func(c *gow.Context) {
        c.JSON(gow.H{
            "code": 0,
            "msg":  "success",
        })
    })

    r.Run()
}

1.2 编译和运行
go build && ./hello
1.3 访问地址
浏览器访问:http://127.0.0.1:8080
curl -i http://127.0.0.1:8080
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Wed, 15 Jul 2020 09:15:31 GMT
Content-Length: 27

{"code":0,"msg":"success"}

2. 做一个网站

包括html模板文件处理和静态资源处理

2.1 目录结构
PROJECT_NAME
├──static
      ├── img
            ├──111.jpg
            ├──222.jpg
            ├──333.jpg
      ├──js
      ├──css
├──views
    ├──index.html
    ├──article
        ├──detail.html
├──main.go
2.2 设置模板目录
r.SetView("views")
2.3 设置静态资源
r.Static("/static", "static")
2.4 模板函数
2.5 演示代码

main.go

package main

import (
    "github.com/gkzy/gow"
)

func main() {
    r := gow.Default()
    r.AutoRender = true //打开html模板渲染
    r.SetView("views") //默认静态目录为views时,可不调用此方法
    r.StaticFile("favicon.ico","static/img/log.png")  //路由favicon.ico
    r.Static("/static", "static")

    //router
    r.Any("/", IndexHandler)
    r.Any("/article/1", ArticleDetailHandler)


    //自定义hello的模板函数
    //在模板文件可通过 {{hello .string}} 来执行
    r.AddFuncMap("hello", func(str string) string {
        return "hello:" + str
    })

    r.Run()
}

//IndexHandler 首页handler
func IndexHandler(c *gow.Context) {
    c.HTML("index.html", gow.H{
        "name":    "gow",
        "package": "github.com/gkzy/gow",
    })
}

//ArticleDetailHandler 文章详情页handler
func ArticleDetailHandler (c *gow.Context){
    c.HTML("article/detail.html", gow.H{
        "title":    "年薪百万的文科专业有哪些?",
    })
}

views/index.html

<html>
<head>
    <title>{{hello .name}}</title>
    <meta charset="utf-8"/>
</head>
<body>
    <h2>{{.name}}</h2>
    <hr>
    <h5>{{.package}}</h5>
</body>
</html>

views/article/detail.html

<html>
<head>
    <title>{{.title}}</title>
    <meta charset="utf-8"/>
    <style>
        img{max-width:600px;}
    </style>
</head>
<body>
    <h2>{{.title}}</h2>
    <hr>
    <p><img src="/static/img/111.jpg"></p>
    <p><img src="/static/img/222.jpg"></p>
    <p><img src="/static/img/333.jpg"></p>
</body>
</html>
运行
go run main.go
或
go build main.go -o app && ./app
访问

https://127.0.0.1:8080/
https://127.0.0.1:8080/article/1


3. 获取值
func GetUser(c *gow.Context){

    //获取字串
    c.GetString("key","default")

    //获取int
    c.GetInt("key",0)

    //获取bool
    c.GetBool("key",false)

    //获取int64
    c.GetInt64("key",-1)

    //获取float
    c.GetFloat("key",0)

    //获取[]string
    var ids []string
    ids = c.GetStrings("ids")  

    //其他方法
    c.GetInt32()
    c.GetInt16()
    c.GetInt8()
    ....
}

获取 request body,并反序列化到 struct


type User struct {
    Nickname string `json:"nickname"`
    QQ       string `json:"qq"`
}

func GetUser(c *Context){
    user := new(User)
    err := c.DecodeJSONBody(&user)
    if err != nil {
        //handler error
    }

    c.JSON(gow.H{
        "user": user,
    })   

}

4. 输出值

支持:json xml string html 等方式输出

JSON

func GetUser(c *Context){

    //default http.StatusOK
    c.JSON(gow.H{
        "nickname":"gow",
        "age":18,
    })

   //或者,指定 http.StatusCode
    c.ServerJSON(200,gow.H{
        "nickname":"gow",
        "age":18,
    })
}

XML

func GetUser(c *Context){

    //default http.StatusOK
    c.XML(gow.H{
        "nickname":"gow",
        "age":18,
    })

   //或者,指定 http.StatusCode
    c.ServerXML(200,gow.H{
        "nickname":"gow",
        "age":18,
    })
}

String

func GetUser(c *Context){

    //default http.StatusOK
    c.String("hello gow...")

   //或者,指定 http.StatusCode
    c.ServerString(200,"hello gow...")
}

File

func GetUser(c *Context){

    //读取并输出
    c.File("go.mod")
}

5. 路由详解
5.1 支持的HTTPMethod
HTTPMethod = map[string]bool{
    "GET":     true,
    "POST":    true,
    "PUT":     true,
    "DELETE":  true,
    "PATCH":   true,
    "OPTIONS": true,
    "HEAD":    true,
    "TRACE":   true,
}
5.2 使用方式

包括基本路由与分组

r := gow.Default()

r.GET(path,handler)
r.POST(path,handler)
r.PUT(path,handler)
r.DELETE(path,handler)
r.PATCH(path,handler)
r.OPTIONS(path,handler)
r.HEAD(path,handler)
r.TRACE(path,handler)
5.3 路由参数
r.Any("/article/:id", ArticleDetailHandler)

获取 param 值

id:=c.Param("id")
5.4 路由分组

main.go

package main

import (
    "github.com/gkzy/gow"
)

func main() {
    r := gow.Default()
    v1 := r.Group("/v1")
    {
        v1.GET("/user/:id", GetUser)
        v1.DELETE("/user/:id", DeleteUser)
    }

    r.Run()
}

func GetUser(c *gow.Context) {
    c.JSON(gow.H{
        "nickname": "新月却泽滨",
        "qq":       "301109640",
    })
}

func DeleteUser(c *gow.Context) {
    c.JSON(gow.H{
        "code": 0,
        "msg": "success",
    })
}

Get

curl -i http://127.0.0.1:8080/v1/user/1


HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Thu, 16 Jul 2020 05:55:16 GMT
Content-Length: 46

{
  "nickname": "新月却泽滨",
  "qq": "301109640"
}

Delete

curl  -X "DELETE" http://127.0.0.1:8080/v1/user/1

{
    "code":0,
    "msg":"success"
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// HTTPMethod  http request method
	HTTPMethod = map[string]bool{
		"GET":     true,
		"POST":    true,
		"PUT":     true,
		"DELETE":  true,
		"PATCH":   true,
		"OPTIONS": true,
		"HEAD":    true,
		"TRACE":   true,
	}
)

Functions

func BytesToString

func BytesToString(b []byte) string

BytesToString converts byte slice to string without a memory allocation.

func DebugPrintError

func DebugPrintError(err error)

func Dir

func Dir(root string, listDirectory bool) http.FileSystem

Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.

func StringToBytes

func StringToBytes(s string) (b []byte)

StringToBytes converts string to byte slice without a memory allocation.

Types

type AppConfig

type AppConfig struct {
	AppName       string //名称
	RunMode       string //运行模式:dev|prod
	HttpAddr      string //"127.0.0.1:8080" or ":8080"
	AutoRender    bool   //是否自动渲染html模板
	Views         string //html 模板目录
	TemplateLeft  string //html模板左符号
	TemplateRight string //html模板右符号
}

AppConfig gow 配置入口 也可以通过此配置文件统一设置app的基础配置 除此之外,也可以通过

	r := gow.Default()
	r.AutoRender = true
 r.AppName = "gow"
 r.SetView("view") 等方式设置

func GetAppConfig

func GetAppConfig() *AppConfig

GetAppConfig 获取配置文件中的信息 默认使用conf/app.conf配置文件

当环境变量 APP_RUN_MODE ="prod"时,使用 conf/prod.app.conf
当环境变量 APP_RUN_MODE ="dev"时,使用 conf/dev.app.conf
没有此环境变量时,使用conf/app.conf

type Context

type Context struct {
	Writer ResponseWriter

	Req *http.Request

	Keys       map[string]interface{}
	Path       string
	Method     string
	IP         string //方便外部其他方法设置IP
	Params     Params
	StatusCode int
	// contains filtered or unexported fields
}

Context gow context

func (*Context) Abort

func (c *Context) Abort()

Abort abort http response

func (*Context) AbortCode

func (c *Context) AbortCode(statusCode int)

Abort abort http response

func (*Context) DecodeJSONBody

func (c *Context) DecodeJSONBody(v interface{}) error

DecodeJSONBody

func (*Context) Download

func (c *Context) Download(data []byte)

Download

func (*Context) Fail

func (c *Context) Fail(statusCode int, err string)

Fail fail http response

func (*Context) File

func (c *Context) File(filePath string)

File read file to http body stream

func (*Context) Form

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

Form

func (*Context) GetBool

func (c *Context) GetBool(key string, def ...bool) (bool, error)

GetBool GetBool

func (*Context) GetCookie

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

GetCookie get request cookie

c.GetCookie("url")

func (*Context) GetFile

func (c *Context) GetFile(key string) (multipart.File, *multipart.FileHeader, error)

GetFile get single from form

func (*Context) GetFiles

func (c *Context) GetFiles(key string) ([]*multipart.FileHeader, error)

GetFiles get []file from form

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string, def ...float64) (float64, error)

GetInt64 GetInt64

func (*Context) GetHeader

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

GetHeader get http request header value by key

func (*Context) GetIP

func (c *Context) GetIP() (ip string)

GetIP get client ip address

func (*Context) GetInt

func (c *Context) GetInt(key string, def ...int) (int, error)

GetInt

func (*Context) GetInt16

func (c *Context) GetInt16(key string, def ...int16) (int16, error)

GetInt16 GetInt16

func (*Context) GetInt32

func (c *Context) GetInt32(key string, def ...int32) (int32, error)

GetInt32 GetInt32

func (*Context) GetInt64

func (c *Context) GetInt64(key string, def ...int64) (int64, error)

GetInt64 GetInt64

func (*Context) GetInt8

func (c *Context) GetInt8(key string, def ...int8) (int8, error)

GetInt8 GetInt8

func (*Context) GetKey

func (c *Context) GetKey(key string) interface{}

GetKey

func (*Context) GetString

func (c *Context) GetString(key string, def ...string) string

GetString 按key返回字串值,可以设置default值

func (*Context) GetStrings

func (c *Context) GetStrings(key string, def ...[]string) []string

GetStrings GetStrings

func (*Context) GetUint16

func (c *Context) GetUint16(key string, def ...uint16) (uint16, error)

GetUint8 GetUint8

func (*Context) GetUint32

func (c *Context) GetUint32(key string, def ...uint32) (uint32, error)

GetUint32 GetUint32

func (*Context) GetUint64

func (c *Context) GetUint64(key string, def ...uint64) (uint64, error)

GetUint64 GetUint64

func (*Context) GetUint8

func (c *Context) GetUint8(key string, def ...uint8) (uint8, error)

GetUint8 GetUint8

func (*Context) HTML

func (c *Context) HTML(name string, data interface{})

HTML

func (*Context) HandlerName

func (c *Context) HandlerName() string

HandlerName get handler name

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax return is ajax request

func (*Context) JSON

func (c *Context) JSON(v interface{})

JSON response successful json format

func (*Context) Next

func (c *Context) Next()

func (*Context) Param

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

Param Param

func (*Context) Query

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

Query Query

func (*Context) Redirect

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

Redirect http redirect like : 301 302 ...

func (*Context) Referer

func (c *Context) Referer() string

Referer get request referer

func (*Context) RequestBody

func (c *Context) RequestBody() []byte

RequestBody request body

func (*Context) SaveToFile

func (c *Context) SaveToFile(fromFile, toFile string) error

SaveToFile saves uploaded file to new path. on server

func (*Context) ServerHTML

func (c *Context) ServerHTML(statusCode int, name string, data interface{})

ServerHTML ServerHTML

func (*Context) ServerJSON

func (c *Context) ServerJSON(statusCode int, data interface{})

ServerJSON response json format

func (*Context) ServerString

func (c *Context) ServerString(statusCode int, msg string)

WriteString response text

func (*Context) ServerXML

func (c *Context) ServerXML(statusCode int, data interface{})

ServerXML response xml

func (*Context) SetCookie

func (c *Context) SetCookie(key, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie set cookie

c.SetCookie("url","22v.net",72*time.Hour,"",true,true)

func (*Context) SetHeader

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

SetHeader set http response header

func (*Context) SetKey

func (c *Context) SetKey(key string, v interface{})

SetKey

func (*Context) Status

func (c *Context) Status(statusCode int)

Status set http status code

func (*Context) String

func (c *Context) String(msg string)

String response text

func (*Context) URL

func (c *Context) URL() string

URL get request url

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent

func (*Context) XML

func (c *Context) XML(data interface{})

XML XML

type Engine

type Engine struct {
	AppName string
	RunMode string
	AppPath string //程序的运行地址
	*RouterGroup

	//template
	HTMLRender render.Render
	FuncMap    template.FuncMap

	AutoRender bool //是否渲染模板

	HandleMethodNotAllowed bool

	UseRawPath            bool
	UnescapePathValues    bool
	RemoveExtraSlash      bool
	RedirectTrailingSlash bool
	RedirectFixedPath     bool
	MaxMultipartMemory    int64
	// contains filtered or unexported fields
}

func Default

func Default() *Engine

func New

func New() *Engine

func (*Engine) AddFuncMap

func (engine *Engine) AddFuncMap(key string, fn interface{})

AddFuncMap add fn func to template func map

func (*Engine) Delims

func (engine *Engine) Delims(left, right string)

Delims set Delims

func (*Engine) NoMethod

func (engine *Engine) NoMethod(handlers ...HandlerFunc)

NoMethod sets the handlers called when... TODO.

func (*Engine) NoRoute

func (engine *Engine) NoRoute(handlers ...HandlerFunc)

NoRoute adds handlers for NoRoute. It return a 404 code by default.

func (*Engine) RouterMap

func (engine *Engine) RouterMap() (routes RoutesInfo)

RoutesMap get all router map

func (*Engine) Run

func (engine *Engine) Run(addr ...string) (err error)

Run

func (*Engine) RunTLS

func (engine *Engine) RunTLS(certFile, keyFile string, addr ...string) (err error)

RunTLS

func (*Engine) ServeHTTP

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

ServeHTTP implement the http.handler interface

func (*Engine) SetAppConfig

func (engine *Engine) SetAppConfig(app *AppConfig)

SetAppConfig 统一配置入口 可使用此方法统一配置,也可以使用其他方法单独设置

func (*Engine) SetView

func (engine *Engine) SetView(path ...string)

SetView set views path 模板目录为 views 时,可不用设置此值

type H

type H map[string]interface{}

H map

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc handler func

func Logger

func Logger() HandlerFunc

gow 2020/07/01 - 14:55:52 | 200 | 44.961µs | 127.0.0.1 | GET "/article/1" Logger

print to console

func Recovery

func Recovery() HandlerFunc

type HandlersChain

type HandlersChain []HandlerFunc

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFunc

Last last handler

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (Params) ByName

func (ps Params) ByName(name string) (va string)

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type ResponseWriter

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

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

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

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

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

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

	// get the http.Pusher for server push
	Pusher() http.Pusher
}

ResponseWriter ...

type RouteInfo

type RouteInfo struct {
	Method      string
	Path        string
	Handler     string
	HandlerFunc HandlerFunc
}

RouteInfo represents a request route's specification which contains method and path and its handler.

type RouterGroup

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

RouterGroup gow routerGroup

func (*RouterGroup) Any

func (group *RouterGroup) Any(path string, handlers ...HandlerFunc)

Any

func (*RouterGroup) DELETE

func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc)

DELETE

func (*RouterGroup) GET

func (group *RouterGroup) GET(path string, handlers ...HandlerFunc)

GET

func (*RouterGroup) Group

func (group *RouterGroup) Group(path string, handlers ...HandlerFunc) *RouterGroup

Group router group

func (*RouterGroup) HEAD

func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc)

HEAD

func (*RouterGroup) Handle

func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc)

Handle Handle

func (*RouterGroup) PATCH

func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc)

PATCH

func (*RouterGroup) POST

func (group *RouterGroup) POST(path string, handlers ...HandlerFunc)

POST

func (*RouterGroup) PUT

func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc)

PUT

func (*RouterGroup) Static

func (group *RouterGroup) Static(relativePath, root string)

Static 静态资源文件 use:

router.Static("/static","static")

func (*RouterGroup) StaticFS

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

StaticFS

func (*RouterGroup) StaticFile

func (group *RouterGroup) StaticFile(relativePath, filepath string)

StaticFile 实现了单个静态文件的路由 router.StaticFile("favicon.ico","./static/favicon.ico")

func (*RouterGroup) TRACE

func (group *RouterGroup) TRACE(path string, handlers ...HandlerFunc)

TRACE

func (*RouterGroup) Use

func (group *RouterGroup) Use(middleware ...HandlerFunc)

Use use middleware

type RouterMap

type RouterMap struct {
	Path        string
	Method      string
	HandlerName string
}

RouterMap

type RoutesInfo

type RoutesInfo []RouteInfo

RoutesInfo defines a RouteInfo array.

Directories

Path Synopsis
lib
logy
like https://gitea.com/lunny/log but made some adjustments
like https://gitea.com/lunny/log but made some adjustments
nsq
//init pu,err:=NewProducer("192.168.0.197",4150) if err!=nil{ //error } b,_:=json.Marshal(obj) //发送 err = pu.Publish("topic",b) if err!=nil{ //error }
//init pu,err:=NewProducer("192.168.0.197",4150) if err!=nil{ //error } b,_:=json.Marshal(obj) //发送 err = pu.Publish("topic",b) if err!=nil{ //error }
oauth/wechat
微信第三方登录相关 公众号支付相关 全局token相关 client:=NewClient(appId,secret) client.SetApiKey("支付的apiKey") ....
微信第三方登录相关 公众号支付相关 全局token相关 client:=NewClient(appId,secret) client.SetApiKey("支付的apiKey") ....
oss
pay/wepay
基础通讯业务实现 sam
基础通讯业务实现 sam
redis
使用方法: 1.
使用方法: 1.
rpc
sms
util
AES CBC PKCS5Padding加/解密 使用 hex.Encode 查看测试文件: aes_cbc_test.go http client 使用github.com/imroc/req库 返回string,如果需要到struct,需要自己反序列化
AES CBC PKCS5Padding加/解密 使用 hex.Encode 查看测试文件: aes_cbc_test.go http client 使用github.com/imroc/req库 返回string,如果需要到struct,需要自己反序列化
use https://github.com/gin-contrib/pprof/blob/master/pprof.go
use https://github.com/gin-contrib/pprof/blob/master/pprof.go

Jump to

Keyboard shortcuts

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