How to create route which is dynamic

时间秒杀一切 提交于 2020-03-27 12:01:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!