英文:
API Discovering its own URL Golang
问题
我已经在Go中创建了一个API,可以通过ElasticSearch搜索或直接访问Element
,然后向JSON负载添加一些数据,并将其返回给用户。当进行搜索时,我会返回一个Element
列表,并且如果用户希望获取更多信息,我希望能够提供一个直接的URL给特定的Element
。
然而,我无法确定应用程序如何确定自己的URL。如果无法确定,URL本身的合理替代方案是什么?
使用net/http包和gorilla/mux进行基于网络的操作。
英文:
I've created an API in Go that can search or directly access an Element
via ElasticSearch, which then adds some data to the JSON payload, and returns that to the user. When searching I'm returning a list of Elements
, and I'd like to be able to give a direct URL to the specific Element
should the user wish to get more information.
However I can't ascertain how the application is supposed to figure out its own URL. In the event that it can't, what would be a reasonable alternative for the URL itself?
Using net/http package and gorilla/mux for net based things.
答案1
得分: 1
你可以通过按名称查找路由,并使用Route.URL
生成URL来“反转”gorilla/mux的URL。
你需要给路由命名,这样你就可以通过Router.Get
轻松查找它。
r := mux.NewRouter()
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
Name("article")
一旦你有了路由,你可以通过将参数传递给URL来构建URL。
url, err := r.Get("article").URL("category", "technology", "id", "42")
// "/articles/technology/42"
请注意,如果你希望自动插入主机,它需要在你的路由上定义:
r := mux.NewRouter()
r.Host("{subdomain}.domain.com").
HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
Name("article")
// url.String() 将是 "http://news.domain.com/articles/technology/42"
url, err := r.Get("article").URL("subdomain", "news",
"category", "technology",
"id", "42")
英文:
You can "reverse" a gorilla/mux url by looking up the route by name, and generating the url with Route.URL
You will want to name your route, so that you can easily look it up via Router.Get
.
r := mux.NewRouter()
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
Name("article")
And once you have the route, you can build a url by passing the parameters to URL
url, err := r.Get("article").URL("category", "technology", "id", "42")
// "/articles/technology/42"
Note that if you want the host to be inserted automatically, it will need to be defined on your route:
r := mux.NewRouter()
r.Host("{subdomain}.domain.com").
HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
Name("article")
// url.String() will be "http://news.domain.com/articles/technology/42"
url, err := r.Get("article").URL("subdomain", "news",
"category", "technology",
"id", "42")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论