答案:通过解析URL查询参数实现分页与筛选,使用Gorilla Mux路由接收page、pageSize、name、city等条件,对用户数据进行过滤并分页返回JSON响应,适用于中小数据集,结合ORM可提升复用性。

在构建 Golang Web API 时,分页和数据筛选是处理列表数据的常见需求。合理的实现方式可以让接口更高效、易用。下面是一个基于 net/http 和 Gorilla Mux 的简单示例,展示如何实现分页与字段筛选功能。
使用 Gorilla Mux 设置路由,接收查询参数进行分页和筛选:
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/users", getUsers).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", r))
}
定义接收查询参数的结构体:
type UserFilter struct {
Page int
PageSize int
Name string
Age int
City string
}
从 URL 查询中提取分页和筛选条件:
立即学习“go语言免费学习笔记(深入)”;
func parseUserFilter(r *http.Request) UserFilter {
page := getIntQuery(r, "page", 1)
pageSize := getIntQuery(r, "pageSize", 10)
if pageSize > 100 {
pageSize = 100 // 限制最大每页数量
}
return UserFilter{
Page: page,
PageSize: pageSize,
Name: r.URL.Query().Get("name"),
City: r.URL.Query().Get("city"),
Age: getIntQuery(r, "age", 0),
}
}
<p>func getIntQuery(r *http.Request, key string, defaultValue int) int {
if val := r.URL.Query().Get(key); val != "" {
if i, err := strconv.Atoi(val); err == nil && i > 0 {
return i
}
}
return defaultValue
}</p>假设我们有一组用户数据,根据 filter 条件过滤并分页返回:
var users = []map[string]interface{}{
{"id": 1, "name": "Alice", "age": 25, "city": "Beijing"},
{"id": 2, "name": "Bob", "age": 30, "city": "Shanghai"},
{"id": 3, "name": "Charlie", "age": 25, "city": "Beijing"},
{"id": 4, "name": "David", "age": 35, "city": "Guangzhou"},
}
<p>func getUsers(w http.ResponseWriter, r *http.Request) {
filter := parseUserFilter(r)</p><pre class='brush:php;toolbar:false;'>var filtered []map[string]interface{}
for _, u := range users {
match := true
if filter.Name != "" && !strings.Contains(u["name"].(string), filter.Name) {
match = false
}
if filter.City != "" && u["city"] != filter.City {
match = false
}
if filter.Age > 0 && u["age"] != filter.Age {
match = false
}
if match {
filtered = append(filtered, u)
}
}
// 分页计算
start := (filter.Page - 1) * filter.PageSize
end := start + filter.PageSize
if start > len(filtered) {
start = len(filtered)
}
if end > len(filtered) {
end = len(filtered)
}
paginated := filtered[start:end]
response := map[string]interface{}{
"data": filtered[start:end],
"pagination": map[string]int{
"page": filter.Page,
"page_size": filter.PageSize,
"total": len(filtered),
"total_page": (len(filtered) + filter.PageSize - 1) / filter.PageSize,
},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)}
发起请求:
GET /api/users?page=1&pageSize=10&name=li&city=Beijing返回结果:
{
"data": [
{"id": 1, "name": "Alice", "age": 25, "city": "Beijing"},
{"id": 3, "name": "Charlie", "age": 25, "city": "Beijing"}
],
"pagination": {
"page": 1,
"page_size": 10,
"total": 2,
"total_page": 1
}
}
这种方式适用于中小型数据集。若对接数据库(如 PostgreSQL 或 MongoDB),可将筛选条件转换为 SQL 或聚合查询,提升性能。
基本上就这些。核心是解析查询参数、做条件匹配、分页切片,并返回结构化响应。实际项目中建议结合 ORM(如 GORM)进一步封装复用逻辑。
以上就是Golang Web API接口分页与数据筛选示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号