在使用Gorilla mux时添加查询参数。

huangapple go评论78阅读模式
英文:

Adding query parameters when using Gorilla mux

问题

我正在学习使用Go语言进行REST API开发,但是我无法弄清楚如何获取特定用户的文档。我的使用情况是一个典型的GET请求,可以获取切片中的所有文档。然而,我希望能够根据用户的ID仅获取属于该用户的文档,例如,ID为1的用户不应该能够获取属于ID为2的用户的文档。我该如何在gorilla mux中添加userID参数并获取所需的数据呢?

文档结构体:

type Document struct {
    Id       string `json:"id"`
    DocName  string `json:"documentName"`
    DocOwner string `json:"documentOwner"`
    UserID   string `json:"userID"`
}

文档切片:

sampleDocuments = []Document{
    {Id: "1", DocName: "身份证", DocOwner: "Beans", UserID: "1"},
    {Id: "2", DocName: "驾驶证", DocOwner: "Kal", UserID: "2"},
    {Id: "3", DocName: "飞行员执照", DocOwner: "Jay", UserID: "2"},
}
英文:

I'm learning REST API development with go and cant figure out how to go about getting user specific documents.
My use case is a typical get request that can fetch all the documents in a slice. However I want to be able to only fetch documents belonging to a user based on their ID such that a user of ID: 1 should not be able to get documents belonging to user of ID:2. How can I go about adding the userID parameters with gorilla mux and fetch desired data.

Document struct

type Document struct {
	Id       string `json:"id"`
	DocName  string `json:"documentName"`
	DocOwner string `json:"documentOwner"`
	UserID string `json:"userID"`
}

Documents slice

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"},
	}

答案1

得分: 1

我成功解决了,如下所示:

// 根据用户ID获取用户的文档
func getDocuments(w http.ResponseWriter, r *http.Request) {

    // 创建一个空的结构体来保存用户的文档
    var userDocs []Document
    vars := mux.Vars(r)
    userid := vars["userID"]

    // 使用用户ID进行筛选
    for _, d := range sampleDocuments {
        if d.UserID == userid {
            userDocs = append(userDocs, d)
        }
    }
    json.NewEncoder(w).Encode(userDocs)
}

请求的URL应该类似于

"...../documents/{userID}"

请注意,这只是一个示例代码片段,其中使用了muxjson包来处理HTTP请求和JSON编码。你需要根据你的实际情况进行适当的修改和调整。

英文:

I managed to figure it out as demonstrated below.

//Get documents belonging to a user based on userID
func getDocuments(w http.ResponseWriter, r *http.Request) {

	//Create an empty struct to hold users documents
	var userDocs []Document
	vars := mux.Vars(r)
	userid := vars["userID"]
    
        // filter using user id
        for _, d := range sampleDocuments {
            if d.UserID == userid {
                userDocs = append(userDocs, d)
          
        }
    }
    json.NewEncoder(w).Encode(userDocs)

}

Request url should look something like this:

"...../documents/{userID}"

答案2

得分: 0

以下是问题的标题中所述的如何使用查询参数。 Gorilla Mux不使用查询参数。

调用Request.FormValue方法来获取查询参数。使用参数的值进行过滤。

func documentHandler(w http.ResponseWriter, r *http.Request) {
    var result []Document
    id := r.FormValue("ID")
    if id == "" {
        // 当未指定用户ID时返回所有文档
        result = sampleDocuments
    } else {
        // 使用用户ID进行过滤
        for _, d := range sampleDocuments {
            if d.UserID == id {
                result = append(result, d)
            }
        }
    }
    json.NewEncoder(w).Encode(result)
}
英文:

Here's how to use a query parameter as stated in the title of the question. The Gorilla Mux does not play a role using query parameters.

Call the Request.FormValue method to get the query parameter. Filter using the value of the parameter.

func documentHandler(w http.ResponseWriter, r *http.Request) {
	var result []Document
	id := r.FormValue("ID")
	if id == "" {
		// Return all documents when no user id specified
		result = sampleDocuments
	} else {
		// filter using user id
		for _, d := range sampleDocuments {
			if d.UserID == id {
				result = append(result, d)
			}
		}
	}
	json.NewEncoder(w).Encode(result)
}

huangapple
  • 本文由 发表于 2023年2月10日 12:06:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定