ch some
This commit is contained in:
66
internal/shared/http.go
Normal file
66
internal/shared/http.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package shared
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultPage = 1
|
||||
DefaultLimit = 10
|
||||
MaxLimit = 100
|
||||
)
|
||||
|
||||
func ParseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func QueryValue(c *gin.Context, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func OptionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
|
||||
raw := QueryValue(c, keys...)
|
||||
if raw == "" {
|
||||
return nil, true
|
||||
}
|
||||
id, ok := ParseID(raw)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return &id, true
|
||||
}
|
||||
|
||||
func ParsePageLimit(c *gin.Context) (page, limit int, ok bool) {
|
||||
page = DefaultPage
|
||||
limit = DefaultLimit
|
||||
|
||||
if raw := QueryValue(c, "page"); raw != "" {
|
||||
p, err := strconv.Atoi(raw)
|
||||
if err != nil || p < 1 {
|
||||
return 0, 0, false
|
||||
}
|
||||
page = p
|
||||
}
|
||||
|
||||
if raw := QueryValue(c, "limit"); raw != "" {
|
||||
l, err := strconv.Atoi(raw)
|
||||
if err != nil || l < 1 || l > MaxLimit {
|
||||
return 0, 0, false
|
||||
}
|
||||
limit = l
|
||||
}
|
||||
|
||||
return page, limit, true
|
||||
}
|
||||
Reference in New Issue
Block a user