日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

go語言beego框架分頁器操作及接口頻率限制示例_Golang

作者:Jeff的技術棧 ? 更新時間: 2022-06-17 編程語言

獲取所有文章數據

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 里面調用方法即可

原文鏈接:https://www.cnblogs.com/guyouyin123/p/14084881.html

欄目分類
最近更新