
本文详解如何使用 go 的 `encoding/json` 包安全解析嵌入在 url 查询字符串中的 json 数据,并指出原始请求中 json 格式错误的问题,提供可运行的修复方案与最佳实践。
在 Go Web 开发中,常需从 HTTP 请求的查询参数(query string)中提取结构化数据。但需特别注意:URL 查询参数本身不是 JSON 容器,必须确保其值是合法、经过 URL 编码的 JSON 字符串。原始问题中的 URL:
http://127.0.0.1:3001/find?field=hostname&field=App&filters=["hostname":"example.com,"type":"vm"]
存在两个关键问题:
- filters 值使用了方括号 [],但内部却是键值对(非 JSON 数组格式),且缺少引号包围 key、逗号后缺失空格、"example.com, 少了闭合引号 —— 这不是有效 JSON;
- 正确形式应为 {"hostname":"example.com","type":"vm"}(对象)或 [{"hostname":"example.com","type":"vm"}](数组),且必须经 url.QueryEscape 编码后传输。
✅ 正确做法如下(以解析 JSON 对象为例):
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func handler(w http.ResponseWriter, r *http.Request) {
// 1. 获取 filters 查询参数值(推荐用 Get 而非 Query()["filters"][0],更安全)
filtersStr := r.URL.Query().Get("filters")
if filtersStr == "" {
http.Error(w, "missing 'filters' parameter", http.StatusBadRequest)
return
}
// 2. 解析 JSON 字符串为 map[string]string
var filters map[string]string
if err := json.Unmarshal([]byte(filtersStr), &filters); err != nil {
http.Error(w, "invalid JSON in 'filters': "+err.Error(), http.StatusBadRequest)
return
}
// 3. 安全提取字段(带存在性检查)
hostname, ok1 := filters["hostname"]
typ, ok2 := filters["type"]
if !ok1 || !ok2 {
http.Error(w, "required fields 'hostname' and/or 'type' missing", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Hostname: %s, Type: %s", hostname, typ)
}
func main() {
http.HandleFunc("/find", handler)
log.Println("Server starting on :3001...")
log.Fatal(http.ListenAndServe(":3001", nil))
}? 关键注意事项:
- ✅ 始终使用 r.URL.Query().Get("key") 获取单值参数,避免索引越界或空切片 panic;
- ✅ json.Unmarshal 要求输入是 []byte,需显式转换 []byte(str);
- ✅ 必须校验 Unmarshal 错误,非法 JSON(如原始示例)会直接返回 json.SyntaxError;
- ✅ 若前端需传复杂结构(如数组、嵌套对象),建议定义结构体并反序列化,而非泛型 map[string]interface{};
- ? 生产环境务必对用户输入做严格校验与超时控制,避免恶意长 JSON 导致内存耗尽。
? 补充:若前端 JavaScript 构造该 URL,应使用:
const filters = JSON.stringify({hostname: "example.com", type: "vm"});
const url = `http://127.0.0.1:3001/find?field=hostname&field=App&filters=${encodeURIComponent(filters)}`;这样服务端才能可靠解析——JSON 内容需先 stringify,再 encodeURIComponent,双重保障格式与传输安全。










