Route

package module
v1.2.12 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2024 License: Apache-2.0 Imports: 17 Imported by: 2

README

golang 原生web路由组件

基于golang http web服务封装 直接兼容golang web服务

环镜: golang >=1.6

依赖组件

hlog(日志组件) gitee.com/tym_hmm/hlog =>

获取路由间方式

go get -u gitee.com/tym_hmm/go-web-router

功能说明

1.路由件已将模板及静态文件[js css]打入二进制包
2.自定义路由中件间
3.兼容golang原生http创建

demo

注意: 1.需在二进制文件创建资源目录
2.在扩口文件最上方引入go 1.6特性(静态资源打入二进制包)

import(
 "embed"
 _ "embed"
)

3.配置资源目录, 在main入口方法之前 //go:embed <资源目录>

main.go

//go:embed Asset
var publicAsset embed.FS

func main() {
  addr := fmt.Sprint(":8080")
  /**初始化路由件 非调试化输出**/
  routerEngine := Route.EngineNew(&publicAsset)

  //调试模式选择输出 EngineNewMode(publicAsset *embed.FS, isDebug bool)
  //routerEngine := Route.EngineNewMode(&publicAsset, true)
  /**
  * 设置模板加载
  * "Asset/template" string 本地模板存放目录
  * ".html" string 模板后缀
  **/
  routerEngine.SetTemplate("Asset/template", ".html")
  
  /**
   自定义json 返回key
   **/
   routerEngine.SetResponseKeyCode("code")
   routerEngine.SetResponseKeyMessage("msg")
   routerEngine.SetResponseKeyData("data")


  /**
   * 设置静态文件加载路由[css js]
   **/
  registerStaticResource(routerEngine, &publicAsset)
  
  /**
  * 设置图片服务路由[不打入到二进制包]
  */
  registerStoreSource(routerEngine)

  /**
   * 注册访问api
   **/
  registerApiRoute(routerEngine)
    
  /**
   * 路由创建
   */
  routerEngine.CreateRouter()
    
  fmt.Printf("http server start in %s", addr)
    
  err := http.ListenAndServe(addr, routerEngine)
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
}



//注册静态资源打包到程序 [css js]
func registerStaticResource(routerEngine *Route.Engine, publicAsset *embed.FS) {
  if publicAsset != nil {
    /**
    * 参数说明
    * "/static/"  对外(如:浏览器 访问地址 http://xxxx.com/static/sss.js)
    * "/asset/source" 源码存放目录(会打入到二进制文件)
    */
    routerEngine.StaticFS("/static/", publicAsset, "/asset/source")
  }
}


/*****本地附件注册 [如上传的图片等 不会打入包]*****/
func registerStoreSource(routerEngine *Route.Engine) {
  /**
  * 参数说明
  * "/upload" 对外访问目录(如[http://xxx.com/upload/a.jpg])
  * "/AssetUpload" 本地存在目录 会在二进制文件相同目录下生成文件夹
  */
  routerEngine.AttachFs("/upload", "/AssetUpload")
}

/** 路由注册 **/
func registerApiRoute(e *Route.Engine) {
  v1 := e.Group("/v1")
  //中间件使用
  v1.UseMiddleware( RequestMiddleware())
  v1.Get("/test", func(c *Route.Context) {
    c.JsonResponse(100, "这是测试", nil)
  })
  v1.Get("/view", func(c *Route.Context) {
    c.Template(nil, "default")
  })
  v1.Get("/viewmultiple", func(c *Route.Context) {
    data := map[string]string{"siteName": ""}
    c.TemplateMultiple(data, []string{ "defaultm","header", "foot"})
  })
}


/** 请求日志拦截[路由中间件] **/
func RequestMiddleware() Route.HttpFunc {
  return func(c *Route.Context) {
    var param interface{}
    if strings.ToLower(c.Request.Method) == "post" {
      param = c.Request.Form
    } else {
      param = c.Request.URL.Query()
    }
    body, _ := ioutil.ReadAll(c.Request.Body)
    c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
    fmt.Printf("request\r\nurl:%s\r\naddr: %s\r\nheader: %s\r\ncooke:%s\r\nmethod: %s\r\nparam:%s\r\nbody:%s\n", c.Request.URL, c.Request.RemoteAddr, c.Request.Header, c.Request.Cookies(), c.Request.Method, param, body)
  }
}

路由接口数据

1.使用*Route.Context 上下文获取当前请求参数

v1.Post("/api", func(c *Route.Context) {
 keyName:= c.GetPostInt("keyName")
})

2.响应json

v1.Get("/test", func(c *Route.Context) {
  c.JsonResponse(100, "这是测试", nil)
})

Documentation

Index

Constants

View Source
const (
	POST = "POST"
	GET  = "GET"
	PUT  = "PUT"
	WS   = "WS"
)
View Source
const (
	//表单提交时去 header需带参数
	//HEADER_REQUEST_TOKEN = "requestToken"
	DEFAULT_SERVER_NAME = "Hmm Server 2.0.0"

	DEFAULT_TEMPLATE_DIR    = "/Asset/Template"
	DEFAULT_TEMPLATE_SUFIXX = ".html"

	DEFAULT_JSON_KEY_CODE = "code"
	DEFAULT_JSON_KEY_MSG  = "message"
	DEFAULT_JSON_KEY_DATA = "data"
)

Variables

This section is empty.

Functions

func AssetHandler

func AssetHandler(prefix string, assets *embed.FS, root string) http.Handler

AssetHandler returns an http.Handler that will serve files from the Assets embed.FS. When locating a file, it will strip the given prefix from the request and prepend the root to the filesystem.

Types

type Context

type Context struct {
	RouterNode *RouterNode
	Request    *http.Request
	Writer     ResponseWriter
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

func (*Context) CJson added in v1.2.12

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

func (*Context) CResponse

func (c *Context) CResponse(data string)

func (*Context) GetCookie added in v1.1.8

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

func (*Context) GetFile

func (c *Context) GetFile(key string) (*FormFile, error)

func (*Context) GetHeaderBool

func (c *Context) GetHeaderBool(key string) bool

func (*Context) GetHeaderFloat

func (c *Context) GetHeaderFloat(key string) float64

func (*Context) GetHeaderInt

func (c *Context) GetHeaderInt(key string) int

func (*Context) GetHeaderInt64

func (c *Context) GetHeaderInt64(key string) int64

func (*Context) GetHeaderString

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

func (*Context) GetParam added in v1.2.10

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

func (*Context) GetPostBool

func (c *Context) GetPostBool(key string) bool

func (*Context) GetPostFloat64

func (c *Context) GetPostFloat64(key string) float64

func (*Context) GetPostFrom

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

func (*Context) GetPostInt

func (c *Context) GetPostInt(key string) int

func (*Context) GetPostInt64 added in v1.1.9

func (c *Context) GetPostInt64(key string) int64

func (*Context) GetPostJson

func (c *Context) GetPostJson() (map[string]interface{}, error)

func (*Context) GetPostJsonParse

func (c *Context) GetPostJsonParse(parse interface{}) error

func (*Context) GetPostString

func (c *Context) GetPostString(key string) (s string)

func (*Context) GetQueryBool

func (c *Context) GetQueryBool(key string) bool

func (*Context) GetQueryFloat

func (c *Context) GetQueryFloat(key string) float64

func (*Context) GetQueryInt

func (c *Context) GetQueryInt(key string) int

func (*Context) GetQueryInt64

func (c *Context) GetQueryInt64(key string) int64

func (*Context) GetQueryString

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

func (*Context) GetResponseKeyCode added in v1.2.11

func (c *Context) GetResponseKeyCode() string

func (*Context) GetResponseKeyData added in v1.2.11

func (c *Context) GetResponseKeyData() string

func (*Context) GetResponseKeyMessage added in v1.2.11

func (c *Context) GetResponseKeyMessage() string

func (*Context) GetUrlParam added in v1.1.6

func (c *Context) GetUrlParam() string

func (*Context) IsAborted

func (c *Context) IsAborted() bool

func (*Context) JsonGzipResponse

func (c *Context) JsonGzipResponse(code int, message string, data interface{})

func (*Context) JsonResponse

func (c *Context) JsonResponse(code int, message string, data interface{})

func (*Context) JsonTrackResponse

func (c *Context) JsonTrackResponse(code int, message string, data interface{})

func (*Context) Next

func (c *Context) Next()

func (*Context) SetCookie added in v1.1.8

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

* maxAge: 过期时间.如果只想设置 Cookie 的保存路径而不想设置存活时间,可以在第三个 参数中传递 nil ; path: cookie 的路径 ; domain: cookie 的路径 Domain 作用域 本地调试配置成 localhost , 正式上线配置成域名 ; secure: 当 secure 值为 true 时,cookie 在 HTTP 中是无效,在 HTTPS 中 才有效 ; httpOnly: 微软对 COOKIE 做的扩展。如果在 COOKIE 中设置了“httpOnly”属性, 则通过程序(JS 脚本、applet 等)将无法读取到 COOKIE 信息,防止 XSS 攻击产生; *

func (*Context) Template

func (c *Context) Template(data interface{}, temp string)

* 模板解析(单模板)

func (*Context) TemplateMultiple

func (c *Context) TemplateMultiple(data interface{}, temps []string)

* 多模板解析

type Engine

type Engine struct {
	Router
	// contains filtered or unexported fields
}

func EngineNew

func EngineNew(publicAsset *embed.FS) *Engine

func EngineNewMode

func EngineNewMode(publicAsset *embed.FS, isDebug bool) *Engine

声明调式模式

func (*Engine) IsDebug

func (engine *Engine) IsDebug(isDebug bool)

func (*Engine) ServeHTTP

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

func (*Engine) SetResponseKeyCode

func (engine *Engine) SetResponseKeyCode(codeKey string)

func (*Engine) SetResponseKeyData

func (engine *Engine) SetResponseKeyData(dataKey string)

func (*Engine) SetResponseKeyMessage

func (engine *Engine) SetResponseKeyMessage(messageKey string)

func (*Engine) SetTemplate

func (engine *Engine) SetTemplate(templateDir, templateSuffix string)

type FilesFilesyste

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

func (FilesFilesyste) Open

func (fs FilesFilesyste) Open(name string) (http.File, error)

type FormFile

type FormFile struct {
	File   multipart.File
	Header *multipart.FileHeader
}

type HandlersChain

type HandlersChain []HttpFunc

type HttpFunc

type HttpFunc func(c *Context)

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter
	Body *bytes.Buffer
}

* context中的响应数据

func (ResponseWriter) Write

func (rw ResponseWriter) Write(b []byte) (int, error)

type Router

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

func (*Router) AttachFs

func (r *Router) AttachFs(relativePath string, root string)

* 注册附件资源

func (*Router) CreateRouter

func (r *Router) CreateRouter()

func (*Router) Get

func (r *Router) Get(path string, handler ...HttpFunc)

func (*Router) GetHandler

func (r *Router) GetHandler(path string, handler ...HttpFunc)

func (*Router) Group

func (r *Router) Group(path string, handlers ...HttpFunc) *Router

*非中间件组*

func (*Router) Post

func (r *Router) Post(path string, handler ...HttpFunc)

func (*Router) StaticFS

func (r *Router) StaticFS(relativePath string, publicAsset *embed.FS, root string)

* 注册静态资源

func (*Router) UseMiddleware

func (r *Router) UseMiddleware(handler ...HttpFunc)

type RouterInfo

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

type RouterNode

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

type RouterParam added in v1.2.10

type RouterParam struct {
	Key   string
	Value string
}

type RouterParams added in v1.2.10

type RouterParams []RouterParam

func (RouterParams) ByName added in v1.2.10

func (ps RouterParams) 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 (RouterParams) Get added in v1.2.10

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

type RouterTree

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

type RouterTrees

type RouterTrees []RouterTree

Jump to

Keyboard shortcuts

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