问题
I am trying to figure out how to create a dynamic route in which I can query certain portions of my struct. For example, say I have the following struct.
type News struct {
Id int64 `json:"id"`
Category string `json:"category"`
ImageUrl string `json:"image_url"`
Title string `json:"title"`
Description string `json:"description"`
Source string `json:"source"`
}
Now, how would I create a route such as
localhost:1234/news?title="sometitle"&source="somesource
回答1:
You can just use query parameters like in your question and handle any known fields as criteria to narrow your search.
The way you actually search these fields depends on where / how your data is stored- you didn't specify this in your question, so I don't know if you're going to query MongoDB, an SQL DB, a map in memory...
You can iterate over your query parameters as follows:
http.HandleFunc("/news", func(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
for field, values := range params {
value := values[len(values)-1] // the last given value of this type
// gradually build your query using field / value
}
})
If you provide more information about how your data is stored, I can give you a more specific answer to help you build your query and retrieve the matching records.
来源:https://stackoverflow.com/questions/45854441/how-to-create-route-which-is-dynamic