Go语言反射与底层编程:原理、应用与注意事项
1. 反射:访问结构体字段标签
在Go语言中,结构体字段标签是一种强大的工具,可用于修改JSON编码等操作。在Web服务器中,多数HTTP处理函数的首要任务是将请求参数提取到局部变量中。我们可以定义一个实用函数 params.Unpack
,借助结构体字段标签让编写HTTP处理函数变得更加便捷。
以下是使用示例:
import "gopl.io/ch12/params"
// search implements the /search URL endpoint.
func search(resp http.ResponseWriter, req *http.Request) {
var data struct {
Labels []string `http:"l"`
MaxResults int `http:"max"`
Exact bool `http:"x"`
}
data.MaxResults = 10 // set default
if err := params.Unpack(req, &data); err != nil {
http.Error(resp, err.Error(), http.StatusBadRequest) // 400
return
}
// ...rest of handler...
fmt.Fprintf(resp, "Search: %+v