使用Gorilla Mux添加查询参数实现用户专属文档获取
使用Gorilla Mux实现用户专属文档的筛选获取
需求说明
通过GET请求获取文档列表,但仅返回与请求中UserID匹配的文档,确保用户只能访问自己的文档。
实现步骤
1. 配置路由接收UserID参数
利用Gorilla Mux的路由规则,在URL路径中定义{userID}参数,以此从请求URL中提取用户ID:
router := mux.NewRouter() router.HandleFunc("/documents/{userID}", getDocumentsByUserID).Methods("GET")
2. 编写处理函数筛选目标文档
在请求处理函数中,先提取URL中的UserID,再遍历文档切片筛选出匹配的条目,最后返回JSON格式结果:
func getDocumentsByUserID(w http.ResponseWriter, r *http.Request) { // 提取URL中的UserID参数 vars := mux.Vars(r) userID := vars["userID"] if userID == "" { w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(map[string]string{"error": "UserID参数不能为空"}) return } // 筛选当前用户的文档 var userDocuments []Document for _, doc := range sampleDocuments { if doc.UserID == userID { userDocuments = append(userDocuments, doc) } } // 返回JSON响应 w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(userDocuments) }
3. 完整可运行代码
package main import ( "encoding/json" "net/http" "github.com/gorilla/mux" ) type Document struct { Id string `json:"id"` DocName string `json:"documentName"` DocOwner string `json:"documentOwner"` UserID string `json:"userID"` } var sampleDocuments = []Document{ {Id: "1", DocName: "Identity card", DocOwner: "Beans", UserID: "1"}, {Id: "2", DocName: "Drivers License", DocOwner: "Kal", UserID: "2"}, {Id: "3", DocName: "Pilots License", DocOwner: "Jay", UserID: "2"}, } func getDocumentsByUserID(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) userID := vars["userID"] if userID == "" { w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(map[string]string{"error": "UserID参数不能为空"}) return } var userDocuments []Document for _, doc := range sampleDocuments { if doc.UserID == userID { userDocuments = append(userDocuments, doc) } } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(userDocuments) } func main() { router := mux.NewRouter() router.HandleFunc("/documents/{userID}", getDocumentsByUserID).Methods("GET") http.ListenAndServe(":8080", router) }
测试验证
启动服务后,通过以下请求测试:
- 获取UserID=1的文档:
GET http://localhost:8080/documents/1,仅返回ID为1的文档 - 获取UserID=2的文档:
GET http://localhost:8080/documents/2,返回ID为2、3的文档
内容的提问来源于stack exchange,提问作者Black Eyed Beans
相关产品推荐
相关产品推荐

