gts

package module
v1.12.5 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2023 License: MIT Imports: 18 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)  
   
    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 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 (
	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) 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) GetString

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

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() ResultBuilder

func (*Context) RespData added in v1.12.1

func (c *Context) RespData() ResourceBuilder

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) SetString

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

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 ErrRespone added in v1.8.26

func ErrRespone(next HandlerFunc) HandlerFunc

type IRouter

type IRouter interface {
	Router(*Router)
}

type M

type M map[string]interface{}

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"` // 200 means success, other means fail
	Data        interface{} `json:"data"`
	Total       int32       `json:"total"`
	TotalPage   int32       `json:"totalPage"`
	PageSize    string      `json:"pageSize"`
	CurrentPage string      `json:"currentPage"`
}

type ResourceBuilder added in v1.8.26

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

func NewResData added in v1.12.1

func NewResData(w http.ResponseWriter) ResourceBuilder

func NewResource added in v1.8.26

func NewResource(data interface{}) ResourceBuilder

success default is true, code default is 200

func (ResourceBuilder) Bd added in v1.12.1

func (builder ResourceBuilder) Bd()

func (ResourceBuilder) Build added in v1.8.26

func (builder ResourceBuilder) Build() *Resource

func (ResourceBuilder) Code added in v1.8.26

func (builder ResourceBuilder) Code(code int) ResourceBuilder

func (ResourceBuilder) CurrentPage added in v1.8.26

func (builder ResourceBuilder) CurrentPage(i string) ResourceBuilder

func (ResourceBuilder) Data added in v1.8.26

func (builder ResourceBuilder) Data(data interface{}) ResourceBuilder

func (ResourceBuilder) JSON added in v1.12.5

func (builder ResourceBuilder) JSON()

func (ResourceBuilder) Message added in v1.8.26

func (builder ResourceBuilder) Message(s string) ResourceBuilder

func (ResourceBuilder) PageSize added in v1.8.26

func (builder ResourceBuilder) PageSize(i string) ResourceBuilder

func (ResourceBuilder) Total added in v1.12.5

func (builder ResourceBuilder) Total(i int32) ResourceBuilder

func (ResourceBuilder) TotalPage added in v1.8.26

func (builder ResourceBuilder) TotalPage(i int32) ResourceBuilder

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
}

func NewResp added in v1.12.1

func NewResult added in v1.8.26

func NewResult() ResultBuilder

success default is true, code default is 200

func (ResultBuilder) Bd added in v1.12.1

func (builder ResultBuilder) Bd()

func (ResultBuilder) Build added in v1.8.26

func (builder ResultBuilder) Build() *Result

func (ResultBuilder) Code added in v1.8.26

func (builder ResultBuilder) Code(code int) ResultBuilder

func (ResultBuilder) Data added in v1.8.26

func (builder ResultBuilder) Data(data interface{}) ResultBuilder

func (ResultBuilder) Error added in v1.8.26

func (builder ResultBuilder) Error(code int) ResultBuilder

func (ResultBuilder) Fail added in v1.8.26

func (builder ResultBuilder) Fail() ResultBuilder

func (ResultBuilder) JSON added in v1.12.5

func (builder ResultBuilder) JSON()

func (ResultBuilder) Message added in v1.8.26

func (builder ResultBuilder) Message(message string) ResultBuilder

func (ResultBuilder) NotFound added in v1.8.26

func (builder ResultBuilder) NotFound() ResultBuilder

func (ResultBuilder) NotPermis added in v1.8.26

func (builder ResultBuilder) NotPermis() ResultBuilder

func (ResultBuilder) OK added in v1.8.26

func (builder ResultBuilder) OK() ResultBuilder

func (ResultBuilder) Success added in v1.8.26

func (builder ResultBuilder) Success() ResultBuilder

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)

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) Static

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

func (*Router) StaticDir

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

func (*Router) StaticFs

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

func (*Router) Use

func (p *Router) Use(h HandlerFun)

添加中间件

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

Jump to

Keyboard shortcuts

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