Skip to content
This repository has been archived by the owner on Dec 7, 2023. It is now read-only.

Commit

Permalink
feat: Add pagination to getRules endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
MerlinKodo committed Nov 21, 2023
1 parent 676caf7 commit 6e3403a
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions hub/route/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package route

import (
"net/http"
"strconv"

"github.com/MerlinKodo/clash-rev/constant"

Expand All @@ -25,9 +26,44 @@ type Rule struct {
}

func getRules(w http.ResponseWriter, r *http.Request) {
pageStr := r.URL.Query().Get("page")
sizeStr := r.URL.Query().Get("size")

var page, size, start, end int
var errPage, errSize error
paginate := true

if pageStr != "" && sizeStr != "" {
page, errPage = strconv.Atoi(pageStr)
size, errSize = strconv.Atoi(sizeStr)

if errPage != nil || errSize != nil || page <= 0 || size <= 0 {
render.Status(r, http.StatusBadRequest)
render.JSON(w, r, render.M{"error": "Invalid page or size number"})
return
}

start = (page - 1) * size
end = start + size
} else {
paginate = false
}

rawRules := tunnel.Rules()
totalRules := len(rawRules)

if !paginate {
start = 0
end = totalRules
} else if start >= totalRules {
start = totalRules
end = totalRules
} else if end > totalRules {
end = totalRules
}

rules := []Rule{}
for _, rule := range rawRules {
for _, rule := range rawRules[start:end] {
r := Rule{
Type: rule.RuleType().String(),
Payload: rule.Payload(),
Expand All @@ -38,7 +74,6 @@ func getRules(w http.ResponseWriter, r *http.Request) {
r.Size = rule.(constant.RuleGroup).GetRecodeSize()
}
rules = append(rules, r)

}

render.JSON(w, r, render.M{
Expand Down

0 comments on commit 6e3403a

Please sign in to comment.