如何创建动态路线 [英] How to create route which is dynamic

查看:131
本文介绍了如何创建动态路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何创建动态路由,在其中可以查询结构的某些部分. 例如,假设我具有以下结构.

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

推荐答案

您可以像在问题中那样使用查询参数,并以任何已知字段为标准来缩小搜索范围.

You can just use query parameters like in your question and handle any known fields as criteria to narrow your search.

您实际搜索这些字段的方式取决于数据的存储位置/存储方式-您未在问题中指定此字段,因此我不知道您是否要查询MongoDB,SQL DB,在内存中映射...

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.

这篇关于如何创建动态路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆