优化结构
This commit is contained in:
@@ -1,11 +1,31 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var errInvalidPositiveUint = errors.New("参数必须是正整数")
|
||||
|
||||
func positiveUint(raw string) (uint, error) {
|
||||
parsed, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64)
|
||||
if err != nil || parsed == 0 || uint64(uint(parsed)) != parsed {
|
||||
return 0, errInvalidPositiveUint
|
||||
}
|
||||
return uint(parsed), nil
|
||||
}
|
||||
|
||||
func positiveUintQuery(c *gin.Context, key string) (uint, error) {
|
||||
return positiveUint(c.Query(key))
|
||||
}
|
||||
|
||||
func positiveUintParam(c *gin.Context, key string) (uint, error) {
|
||||
return positiveUint(c.Param(key))
|
||||
}
|
||||
|
||||
func page(c *gin.Context) (int, int, error) {
|
||||
var value, size int
|
||||
if raw, exists := c.GetQuery("page"); exists && raw != "" {
|
||||
@@ -25,14 +45,18 @@ func page(c *gin.Context) (int, int, error) {
|
||||
return value, size, nil
|
||||
}
|
||||
|
||||
func IDsFromQuery(c *gin.Context) []uint {
|
||||
func IDsFromQuery(c *gin.Context) ([]uint, error) {
|
||||
values := c.QueryArray("IDs[]")
|
||||
if len(values) == 0 {
|
||||
return nil, errInvalidPositiveUint
|
||||
}
|
||||
ids := make([]uint, 0, len(values))
|
||||
for _, value := range values {
|
||||
id, _ := strconv.ParseUint(value, 10, 64)
|
||||
if id > 0 {
|
||||
ids = append(ids, uint(id))
|
||||
id, err := positiveUint(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user