gts

package module
v1.26.10 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: MIT Imports: 23 Imported by: 0

README

gts Web Framework

golang搭建极简的原生WEB后台项目


  import (  
    "github.com/gkyh/gts"  
    "net/http"  
   )  
 
   func main() {  
     route := gts.New()  
     
     //3600 session 超时时间;单位:秒;
     //0 cookie 储存时间,0 关闭浏览器失效,>0超时时间
     route.Cookie("gosessionid", 3600, 0)  
     //实现RouteLogger接口的均可
     //type RouteLogger interface {
     //     Println(v ...interface{})
     // }
     var logger *log.Logger
     route.Logger(logger)
       

    //静态文件,参数1 请求url路径,参数2 请求文件路径
    route.Static("/public", "./public/") 

    //Favicon.ico文件路径  
    route.Favicon("./")

    //中间件 
    route.UseErrResp() 
    route.Use(ws)  
    route.Use(ws2)   
    route.Route("/test", testHandler, HandleIterceptor)  
    route.Group("/group", groupHandler)  
      
    route.Get("/login", func(req *http.Request,ctx *gts.Context) {  

      session:= ctx.Session()
      session.Set("username", "root")
      ctx.WriteString(200, "login")   
    })  

    //注册路由必须现实 func(req *http.Request, c *gts.Context) 格式的函数
    route.Get("/user", func(req *http.Request, c *gts.Context) {  

      session:= c.Session()  
      user := c.Get("username")  
      if user !=nil {  
        c.WriteString(200, user.(string))   
      } else {  
        c.WriteString(404, "not found")  
      }  
    })  

    //route.Any("/any", func)  添加get 和 post 方法
    //route.Post("/post", func)  
    //route.Get("/get", func)  
    //route.Delete("/delete", func)
    // 原生http.handler
    route.Handler("/path", func(w http.ResponseWriter, req *http.Request){
	})
   
    route.Run(":8080")

  }
  func groupHandler(route *gts.Router){  
    
    //路由:/group/test
  	route.Get("/test",testFunc)
	  route.Post("/test",testFunc)
  }
  //中间件定义
  func ws(next gts.HandlerFunc) gts.HandlerFunc {  
     return func(ctx *gts.Context) {  

     ip := getRemoteIp(ctx.Request)
      fmt.Println("request ip:" + ip)

	   v := map[string]interface{}{
			"reqIP": ip,
	   }
	  ctx.Set("context", v)
	  next(ctx)

    }  
  }  
  
  //拦截器,(也是中间件的一种)
  func HandleIterceptor(next gts.HandlerFunc) gts.HandlerFunc {. 
    return func(c *gts.Context) {   
  
    ip := r.RemoteAddr   
    fmt.Println("handleIterceptor,ip:" + ip)   

    user, _ := c.SessionVal("username")
    if user != nil { 

      fmt.Println(user.(string))   
  
      v := gts.ContextValue{   
        "reqIP":    ip,   
        "username": user.(string),   
      }  
  
      c.Set("context", v)  
      next(c)  
      return  
    }  
  
    c.Redirect("/login")    
    return   
  
  }. 
  }

###TestConterller


var testHandler *TestConterller = new(TestConterller)   
  
type TestConterller struct {    
}   
//必须在Router方法中添加路由
func (p *TestConterller) Router(router *gts.Router) {

    router.Any("/list", p.mlogHandler)  

}  

func (p *TestConterller) ListHanlder(req *http.Request,c *gts.Context) {  

    req.ParseForm()
    data := req.FormValue("data")
    
    // 接收数据解析到struct
    form := &ReqForm{}
    err := gts.Bind(req, form)

}  

Context 返回数据方法


  Write(b []byte)  
  
  WriteString(status int, s string)

  HTML(status int, html string)  
  
  JSON(status int, m map[string]interface{})  
  
  Result(s string)   
  
  Msg(s string) //=》{"code": 200, "msg": s}  
  
  OK()  //=〉{"code": 200, "msg": "处理成功"}
  
  Redirect(url string)   

Documentation

Index

Constants

View Source
const BadGateway int = 502 //外部异常,通常为请求第三方
View Source
const BadReq int = 400 //提交错误
View Source
const Exception int = 500 //服务器异常,程序抛出异常
View Source
const (
	ExpiresTime = 24
)
View Source
const Failed int = 410 //请求业务无法成功受理,业务自定义
View Source
const Forbidden int = 405 //访问被禁止
View Source
const NotAuthor int = 401 //认证失败或操作超时
View Source
const NotLimit int = 501 //不接受请求,如IP被限制
View Source
const NotPermis int = 403 //没有操作权限
View Source
const Repeat int = 402 //请求处理已完成或重复请求
View Source
const StatusError int = 406 //请求业务状态错误
View Source
const StatusNotFound int = 404 // fail,reason is not found
View Source
const StatusOk int = 200 // success
View Source
const StatusUnknown int = 500 // fail,reason is unknown
View Source
const Unavilable int = 503 //请求未能应答

Variables

View Source
var (
	BitcoinAlphabet = NewAlphabet("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
	IPFSAlphabet    = NewAlphabet("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
	FlickrAlphabet  = NewAlphabet("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")
	RippleAlphabet  = NewAlphabet("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz")
)

Alphabet: copy from https://en.wikipedia.org/wiki/Base58

View Source
var (
	ErrTokenExpired   = errors.New("token has expired")
	ErrInvalidToken   = errors.New("invalid token")
	ErrTokenMalformed = errors.New("token is malformed")
)

错误定义

View Source
var (
	ErrorInvalidBase58String = errors.New("invalid base58 string")
)

Errors

View Source
var (
	Type = map[string]int{
		"Any":    0,
		"GET":    1,
		"POST":   2,
		"DELETE": 3,
		"PUT":    4,
	}
)

Functions

func Bind

func Bind(request *http.Request, result interface{}) (err error)

func BindForm

func BindForm(values map[string][]string, result interface{}) (err error)

func BindWith

func BindWith(source map[string]interface{}, result interface{}) (err error)

func BindWithAdvanced

func BindWithAdvanced(source map[string]interface{}, result interface{}, tag, cleanedTag string) error

func BindWithTag

func BindWithTag(source map[string]interface{}, result interface{}, tag string) error

func Decode

func Decode(input string, alphabet *Alphabet) ([]byte, error)

Decode docode with custom alphabet

func DelEx

func DelEx(key string) error

func Encode

func Encode(input []byte, alphabet *Alphabet) string

Encode encode with custom alphabet

func GetEx

func GetEx(key string) ([]byte, error)

func SetEx

func SetEx(key string, value []byte, time int32) error

Types

type Alphabet

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

Alphabet The base58 alphabet object.

func NewAlphabet

func NewAlphabet(alphabet string) *Alphabet

NewAlphabet create a custom alphabet from 58-length string. Note: len(rune(alphabet)) must be 58.

func (Alphabet) String

func (alphabet Alphabet) String() string

Alphabet's string representation

type Context

type Context struct {
	Writer   http.ResponseWriter
	Request  *http.Request
	Sessions Session
}

func (*Context) Bind added in v1.25.11

func (c *Context) Bind(i interface{}) error

func (*Context) CorsHandler added in v1.12.15

func (c *Context) CorsHandler()

func (*Context) Err

func (c *Context) Err(code int32, s string)

func (*Context) FormValue

func (c *Context) FormValue(key, val string) string

func (*Context) Get

func (c *Context) Get(key string) map[string]interface{}

func (*Context) GetCookie added in v1.12.6

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

func (*Context) GetName added in v1.12.20

func (c *Context) GetName() string

func (*Context) GetRid added in v1.12.20

func (c *Context) GetRid() int32

func (*Context) GetString

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

func (*Context) GetUid added in v1.12.20

func (c *Context) GetUid() int32

func (*Context) HTML

func (c *Context) HTML(status int, s string)

func (*Context) JSON

func (c *Context) JSON(status int, m map[string]interface{})

func (*Context) Map

func (c *Context) Map(m map[string]interface{})

func (*Context) Msg

func (c *Context) Msg(code int32, s string)

func (*Context) NoAuth added in v1.12.2

func (c *Context) NoAuth()

func (*Context) NoPermis added in v1.12.2

func (c *Context) NoPermis()

func (*Context) NotFound added in v1.12.2

func (c *Context) NotFound()

func (*Context) OK

func (c *Context) OK()

func (*Context) Redirect

func (c *Context) Redirect(url string)

func (*Context) ReqValue

func (c *Context) ReqValue(params ...string) map[string]interface{}

func (*Context) Resp added in v1.12.1

func (c *Context) Resp() *RespBuilder

func (*Context) RespData added in v1.12.1

func (c *Context) RespData() *RespBuilder

func (*Context) Result

func (c *Context) Result(m interface{})

func (*Context) Session

func (c *Context) Session() *Store

func (*Context) SessionID

func (c *Context) SessionID() (string, bool)

func (*Context) Set

func (c *Context) Set(key string, v map[string]interface{})

func (*Context) SetCookie added in v1.12.6

func (c *Context) SetCookie(key, value string, minute int, args ...bool)

func (*Context) SetCookieAndDomain added in v1.12.15

func (c *Context) SetCookieAndDomain(key, value string, args ...bool)

使用根域名,通常用于跨域访问cookie,过期时间为cookieExpiresTime

func (*Context) SetString

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

func (*Context) UidAuth added in v1.12.20

func (c *Context) UidAuth(id int32)

func (*Context) Write

func (c *Context) Write(status int, b []byte)

func (*Context) WriteString

func (c *Context) WriteString(s string)

type CookieSession

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

Session会话管理

func NewCookieSession

func NewCookieSession(cookieName string, maxLifeTime, cookieTime int64, secure bool) *CookieSession

创建会话管理器(cookieName:在浏览器中cookie的名字;maxLifeTime:最长生命周期)

func (*CookieSession) Del

func (ses *CookieSession) Del(w http.ResponseWriter, r *http.Request)

结束Session

func (*CookieSession) GC

func (ses *CookieSession) GC()

GC回收

func (*CookieSession) Get

func (ses *CookieSession) Get(r *http.Request, key string) (interface{}, bool)

func (*CookieSession) GetLastAccessTime

func (ses *CookieSession) GetLastAccessTime(sessionID string) time.Time

更新最后访问时间

func (*CookieSession) GetSessionIDList

func (ses *CookieSession) GetSessionIDList() []string

得到sessionID列表

func (*CookieSession) GetVal

func (ses *CookieSession) GetVal(sessionID string, key string) interface{}

得到session里面的值

func (*CookieSession) New

在开始页面登陆页面,开始Session

func (*CookieSession) Remove

func (ses *CookieSession) Remove(sessionID string)

结束session

func (*CookieSession) SessionID

func (ses *CookieSession) SessionID(r *http.Request) (string, bool)

func (*CookieSession) Set

func (ses *CookieSession) Set(r *http.Request, key string, value interface{}) bool

func (*CookieSession) SetVal

func (ses *CookieSession) SetVal(sessionID string, key string, value interface{}) error

设置session里面的值

type HandlerFun

type HandlerFun func(HandlerFunc) HandlerFunc

type HandlerFunc

type HandlerFunc func(*http.Request, *Context)

func Cors added in v1.12.15

func Cors(next HandlerFunc) HandlerFunc

func ErrRespone added in v1.8.26

func ErrRespone(next HandlerFunc) HandlerFunc

type IRouter

type IRouter interface {
	Router(*Router)
}

type JWTManager added in v1.12.13

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

JWT管理器

func NewJWTManager added in v1.12.13

func NewJWTManager(secretKey string) *JWTManager

创建新的JWT管理器

func (*JWTManager) CleanupBlacklist added in v1.12.13

func (m *JWTManager) CleanupBlacklist()

清理过期的黑名单令牌

func (*JWTManager) GenerateToken added in v1.12.13

func (m *JWTManager) GenerateToken(config TokenConfig, customClaims map[string]interface{}) (string, error)

生成令牌

func (*JWTManager) RevokeToken added in v1.12.13

func (m *JWTManager) RevokeToken(tokenString string, duration time.Duration)

吊销令牌

func (*JWTManager) VerifyToken added in v1.12.13

func (m *JWTManager) VerifyToken(tokenString string) (map[string]interface{}, error)

验证令牌

type M

type M map[string]interface{}

type Payload added in v1.12.13

type Payload struct {
	Issuer   string `json:"iss,omitempty"`
	Subject  string `json:"sub,omitempty"`
	Audience string `json:"aud,omitempty"`

	IssuedAt  int64 `json:"iat,omitempty"`
	ExpiresAt int64 `json:"exp,omitempty"`
	NotBefore int64 `json:"nbf,omitempty"`
}

Payload 使用更多标准字段 omitempty 是 Go 语言中 JSON 编码的一个特殊标签,它的作用是在序列化 JSON 时, 如果对应的字段为零值(nil、空字符串、0、false 等),则不会被包含在生成的 JSON 中。

type Provider

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

—————————————————————————— 会话

type RedisPool

type RedisPool struct {
	Pool *redis.Pool
}

type RedisSession

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

Session会话管理

func NewRedisSession

func NewRedisSession(cookieName string, maxLifeTime, cookieTime int64, secure bool, RedisHost, RedisPwd string, database ...int) *RedisSession

创建会话管理器(cookieName:在浏览器中cookie的名字;maxLifeTime:最长生命周期)

func (*RedisSession) Del

func (ses *RedisSession) Del(w http.ResponseWriter, r *http.Request)

结束Session

func (*RedisSession) Get

func (ses *RedisSession) Get(r *http.Request, key string) (interface{}, bool)

func (*RedisSession) GetSessionIDList

func (ses *RedisSession) GetSessionIDList() []string

得到sessionID列表

func (*RedisSession) GetVal

func (ses *RedisSession) GetVal(sessionID string, key string) interface{}

得到session里面的值

func (*RedisSession) New

func (ses *RedisSession) New(w http.ResponseWriter) string

在开始页面登陆页面,开始Session

func (*RedisSession) Remove

func (ses *RedisSession) Remove(sessionID string)

结束session

func (*RedisSession) SessionID

func (ses *RedisSession) SessionID(r *http.Request) (string, bool)

func (*RedisSession) Set

func (ses *RedisSession) Set(r *http.Request, key string, value interface{}) bool

func (*RedisSession) SetVal

func (ses *RedisSession) SetVal(sessionID string, key string, value interface{}) error

设置session里面的值

type Resource added in v1.8.26

type Resource struct {
	Message     string      `json:"msg"`
	Code        int         `json:"code"`
	Data        interface{} `json:"data"`
	Total       int32       `json:"total"`
	TotalPage   int32       `json:"totalPage"`
	PageSize    string      `json:"pageSize"`
	CurrentPage string      `json:"currentPage"`
}

type RespBuilder added in v1.25.9

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

---- Builder ----

func NewResp added in v1.12.1

func NewResp(w http.ResponseWriter) *RespBuilder

func (*RespBuilder) Code added in v1.25.9

func (b *RespBuilder) Code(code int) *RespBuilder

---- 通用方法 ----

func (*RespBuilder) CurrentPage added in v1.25.9

func (b *RespBuilder) CurrentPage(page string) *RespBuilder

func (*RespBuilder) Data added in v1.25.9

func (b *RespBuilder) Data(data interface{}) *RespBuilder

func (*RespBuilder) Error added in v1.25.9

func (b *RespBuilder) Error(code int) *RespBuilder

func (*RespBuilder) Fail added in v1.25.9

func (b *RespBuilder) Fail() *RespBuilder

失败(未知原因)

func (*RespBuilder) JSON added in v1.25.9

func (b *RespBuilder) JSON()

---- 输出 ----

func (*RespBuilder) Message added in v1.25.9

func (b *RespBuilder) Message(msg string) *RespBuilder

func (*RespBuilder) NotFound added in v1.25.9

func (b *RespBuilder) NotFound() *RespBuilder

未找到

func (*RespBuilder) NotPermis added in v1.25.9

func (b *RespBuilder) NotPermis() *RespBuilder

没有操作权限

func (*RespBuilder) OK added in v1.25.9

func (b *RespBuilder) OK() *RespBuilder

OK(只设置状态码)

func (*RespBuilder) PageSize added in v1.25.9

func (b *RespBuilder) PageSize(size string) *RespBuilder

func (*RespBuilder) Success added in v1.25.9

func (b *RespBuilder) Success() *RespBuilder

成功

func (*RespBuilder) Total added in v1.25.9

func (b *RespBuilder) Total(total int32) *RespBuilder

func (*RespBuilder) TotalPage added in v1.25.9

func (b *RespBuilder) TotalPage(totalPage int32) *RespBuilder

type Result added in v1.8.26

type Result struct {
	Message string      `json:"msg"`
	Code    int         `json:"code"` // 200 means success, other means fail
	Data    interface{} `json:"data"`
}

type ResultBuilder added in v1.8.26

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

type RouteLogger

type RouteLogger interface {
	Println(v ...interface{})
}

type Router

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

func New

func New() *Router

func (*Router) Any

func (p *Router) Any(relativePath string, handler HandlerFunc, filter ...HandlerFun)

func (*Router) Cookie

func (p *Router) Cookie(cookieName string, maxLifeTime, cookieTime int64, secure bool)

func (*Router) Delete

func (p *Router) Delete(relativePath string, handler HandlerFunc, filter ...HandlerFun)

func (*Router) Favicon

func (p *Router) Favicon(dirPath string)

func (*Router) File

func (p *Router) File(relativePath string, filePath string, filter ...HandlerFun)

func (*Router) Get

func (p *Router) Get(relativePath string, handler HandlerFunc, filter ...HandlerFun)

func (*Router) GetSession

func (p *Router) GetSession(r *http.Request, key string) interface{}

func (*Router) Group

func (p *Router) Group(url string, h func(r *Router), params ...HandlerFun)

func (*Router) Handler

func (p *Router) Handler(relativePath string, h http.HandlerFunc, f ...HandlerFun)

route.handler("/user", handlerFunc) 访问: /user/abc 匹配

func (*Router) Logger

func (p *Router) Logger(log RouteLogger)

func (*Router) NoFound

func (p *Router) NoFound(handler http.HandlerFunc)

func (*Router) Post

func (p *Router) Post(relativePath string, handler HandlerFunc, filter ...HandlerFun)

func (*Router) Put

func (p *Router) Put(relativePath string, handler HandlerFunc, filter ...HandlerFun)

func (*Router) Redis

func (p *Router) Redis(cookieName string, maxLifeTime, cookieTime int64, secure bool, RedisHost, RedisPwd string, database ...int)

func (*Router) Route

func (p *Router) Route(url string, i IRouter, params ...HandlerFun)

func (*Router) Run added in v1.8.26

func (p *Router) Run(addr string)

func (*Router) ServeHTTP

func (p *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Router) ServerTimeout added in v1.8.26

func (p *Router) ServerTimeout(readTimeout, writeTimeout int)

func (*Router) SessionExpires added in v1.12.19

func (p *Router) SessionExpires(minute int)

func (*Router) Static

func (p *Router) Static(relativePath string, dirPath string)

常规静态资源,如 css/js/images

func (*Router) StaticDir

func (p *Router) StaticDir(relativePath string, dir string)

指定目录结构,只能访问文件,无法递归目录

func (*Router) StaticFs

func (p *Router) StaticFs(relativePath string, handler http.HandlerFunc)

自行处理文件实现,如OSS/FileDB/S3/虚拟文件系统

func (*Router) Use

func (p *Router) Use(h HandlerFun)

添加中间件

func (*Router) UseCors added in v1.12.15

func (p *Router) UseCors()

func (*Router) UseErrResp added in v1.8.26

func (p *Router) UseErrResp()

type Session

type Session interface {
	New(w http.ResponseWriter) string
	Del(w http.ResponseWriter, r *http.Request)
	Remove(sessionID string)
	SetVal(sessionID string, key string, value interface{}) error
	GetVal(sessionID string, key string) interface{}
	SessionID(r *http.Request) (string, bool)
	Set(r *http.Request, key string, value interface{}) bool
	Get(r *http.Request, key string) (interface{}, bool)
}

type Store

type Store struct {
	Sessions  Session
	SessionID string
	Response  http.ResponseWriter
}

func (*Store) Del

func (c *Store) Del()

func (*Store) Get

func (c *Store) Get(key string) interface{}

func (*Store) Set

func (c *Store) Set(key string, value interface{}) bool

type TokenConfig added in v1.12.13

type TokenConfig struct {
	Issuer         string
	Subject        string
	Audience       string
	ExpirationTime time.Duration
	NotBefore      time.Duration
}

配置结构体,支持更灵活的配置

Jump to

Keyboard shortcuts

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