您现在的位置是:网站首页> 编程资料编程资料
go语言beego框架分页器操作及接口频率限制示例_Golang_
2023-05-26
358人已围观
简介 go语言beego框架分页器操作及接口频率限制示例_Golang_
获取所有文章数据
o := orm.NewOrm() qs := o.QueryTable("Article") 12 获取总条数
count, _ := qs.Count() 1
设置每页的条数
pageSetNum := 2 1
总页数和当前页码
// 总页数 pageCount := math.Ceil((float64(count) / float64(pageSetNum))) // 获取当前页码 pageNum, err := this.GetInt("pageNum") if err != nil { pageNum = 1 } 1234567 获取分页数据
//存储分页数据的切片 articles := new([]models.Article) //获取分页数据 qs.Limit(pageSetNum, pageSetNum*(pageNum - 1)).All(articles) 1234
返回数据
beego.Info(*articles) this.Data["articles"] = *articles this.Data["count"] = count this.Data["pageCount"] = pageCount this.Data["pageNum"] = pageNum this.TplName = "index.html"
beego接口频率限制
package utils import ( "github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/astaxie/beego/logs" "github.com/ulule/limiter" "github.com/ulule/limiter/v3" "github.com/ulule/limiter/v3/drivers/store/memory" "net/http" "strings" ) // RateLimiter this is a struct type RateLimiter struct { Limiter *limiter.Limiter Username string UserType string UserToken string RemainTimes int MaxTimes int } func RateLimit(rateLimit *RateLimiter, ctx *context.Context) { var ( limiterCtx limiter.Context err error req = ctx.Request ) opt := limiter.Options{ IPv4Mask: limiter.DefaultIPv4Mask, IPv6Mask: limiter.DefaultIPv6Mask, TrustForwardHeader: false, } ip := limiter.GetIP(req, opt) if strings.HasPrefix(ctx.Input.URL(), "/") { limiterCtx, err = rateLimit.Limiter.Get(req.Context(), ip.String()) } else { logs.Info("The api request is not track ") } if err != nil { ctx.Abort(http.StatusInternalServerError, err.Error()) return } if limiterCtx.Reached { logs.Debug("Too Many Requests from %s on %s", ip, ctx.Input.URL()) // refer to https://beego.me/docs/mvc/controller/errors.md for error handling ctx.Abort(http.StatusTooManyRequests, "429") return } } func PanicError(e error) { if e != nil { panic(e) } } func RunRate() { // 限制每秒登录的请求次数 theRateLimit := &RateLimiter{} // 100 reqs/second: "100-S" "100-s" loginMaxRate := beego.AppConfig.String("total_rule::reqrate") loginRate, err := limiter.NewRateFromFormatted(loginMaxRate + "-s") PanicError(err) theRateLimit.Limiter = limiter.New(memory.NewStore(), loginRate) beego.InsertFilter("/*", beego.BeforeRouter, func(ctx *context.Context) { RateLimit(theRateLimit, ctx) }, true) } 在main.go 里面调用方法即可
以上就是go语言beego框架分页器操作及接口频率限制示例的详细内容,更多关于go beego框架分页器操作接口频率限制的资料请关注其它相关文章!
您可能感兴趣的文章:
相关内容
- Go处理json数据方法详解(Marshal,UnMarshal)_Golang_
- Go基础教程系列之WaitGroup用法实例详解_Golang_
- GO语言协程互斥锁Mutex和读写锁RWMutex用法实例详解_Golang_
- Go实现线程池(工作池)的两种方式实例详解_Golang_
- go语言beego框架web开发语法笔记示例_Golang_
- golang beego框架路由ORM增删改查完整案例_Golang_
- GO语言入门学习之基本数据类型字符串_Golang_
- Beego中ORM操作各类数据库连接方式详细示例_Golang_
- Go基础教程系列之Go接口使用详解_Golang_
- Go基础教程系列之import导入包(远程包)和变量初始化详解_Golang_
