如何在Go Fiber中保持响应JSON的键顺序与定义一致?
问题
我在Go Fiber的接口中编写了如下查询代码:
query := `SELECT * FROM "user" WHERE username = $1` row := db.QueryRow(query, user.Username) var ( usn string pass string created_at string id int ) // binds the above variables to "row" that is returned by "db.QueryRow" // "row.Scan" will also release the connection if err := row.Scan(&usn, &pass, &created_at, &id); err != nil { return c.Status(500).JSON(fiber.Map{ "error": err, }) } return c.JSON(fiber.Map{ "username": usn, "password": pass, "created_at": created_at, "id": id, })
请求该接口时,得到的响应为:
{ "created_at": "timestamp", "id": 3, "password": "123", "username": "bro" }
我希望响应的键顺序与fiber.Map中定义的顺序一致,即:
{ "username": "bro", "password": "123", "created_at": "timestamp", "id": 3, }
请问该如何实现?
解决方案
Go语言中的map(fiber.Map本质是map[string]interface{})是无序集合,序列化后键的顺序无法保证。要实现固定顺序的JSON输出,推荐以下两种方法:
方法1:使用结构体替代fiber.Map
定义对应结构体,通过json标签指定键名,结构体字段的声明顺序就是JSON输出的键顺序:
type UserResponse struct { Username string `json:"username"` Password string `json:"password"` CreatedAt string `json:"created_at"` ID int `json:"id"` }
返回时实例化结构体并传入c.JSON:
return c.JSON(UserResponse{ Username: usn, Password: pass, CreatedAt: created_at, ID: id, })
这是Go生态中最规范的实现方式,同时能获得类型安全检查的额外收益。
方法2:使用有序Map(第三方依赖)
若不想定义结构体,可引入支持有序键的第三方Map库(如elliotchance/orderedmap),这类库会保留键的插入顺序。示例代码如下:
import "github.com/elliotchance/orderedmap" // ... om := orderedmap.NewOrderedMap() om.Set("username", usn) om.Set("password", pass) om.Set("created_at", created_at) om.Set("id", id) return c.JSON(om)
注意需确保第三方库实现了json.Marshaler接口,Fiber才能正确序列化它。
内容的提问来源于stack exchange,提问作者me-an-ape
相关产品推荐
相关产品推荐

