登录
首页 >  Golang >  Go教程

GolangAPI分页与筛选实战教程

时间:2025-10-13 22:02:27 396浏览 收藏

本篇文章向大家介绍《Golang API分页与数据筛选实战教程》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

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

Golang Web API接口分页与数据筛选示例

在构建 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 查询中提取分页和筛选条件:

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)进一步封装复用逻辑。

本篇关于《GolangAPI分页与筛选实战教程》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>