<p>I need some help implementing paths such as /person/name/Stat in my go app. There is a list of persons with me. So only valid person names shall pass forward in /person/(name) /. </p>
<hr/>**评论:**<br/><br/>gogroob: <pre><p>If the path is simple, like <code>/person/name</code> then you can slice the path on the length of <code>/person/</code></p>
<pre><code>func person(w http.ResponseWriter, r *http.Request) {
name := r.URL.Path[len("/person/"):]
w.Write([]byte(name))
}
</code></pre></pre>Gacnt: <pre><p>Even easier to just use path.Base()</p></pre>elithrar_: <pre><p>If you're not interested in using an existing router/mux library (of which there are <em>many</em>), then you can look at their pattern matching code:</p>
<ul>
<li><a href="https://github.com/gorilla/mux/blob/master/route.go" rel="nofollow">https://github.com/gorilla/mux/blob/master/route.go</a></li>
<li><a href="https://github.com/gorilla/muxy/blob/master/matchers/mpath/mpath.go" rel="nofollow">https://github.com/gorilla/muxy/blob/master/matchers/mpath/mpath.go</a></li>
<li><a href="https://github.com/goji/goji/blob/master/pat/pat.go" rel="nofollow">https://github.com/goji/goji/blob/master/pat/pat.go</a></li>
<li><a href="https://github.com/julienschmidt/httprouter/blob/master/path.go" rel="nofollow">https://github.com/julienschmidt/httprouter/blob/master/path.go</a></li>
</ul>
<p>The simple approach would be to use mux with a path of <code>/persons/{name}/stat</code> and then call <code>mux.Vars(r)</code> to lookup whether <code>vars["name"]</code> exists in 'a list of persons'.</p></pre>--Mister--j: <pre><p>Will it be a good idea to use query parameters instead of paths. This is in terms of pattern matching and handler definitions.</p></pre>maruwan: <pre><p>The stdlib does prefix matching only. Ask yourself, why is the <code>/stat</code> part behind the person name? why not <code>/person-stat?p=name</code>?</p></pre>gbitten: <pre><p>You can use <a href="https://golang.org/pkg/net/http/#ServeMux.HandleFunc" rel="nofollow">http.HandleFunc</a>. In this function, a pattern ending in a slash defines a subtree (details <a href="https://golang.org/pkg/net/http/#ServeMux" rel="nofollow">here</a>). So, you can register a handler function with the pattern "/person/" like the below example. </p>
<pre><code>package main
import (
"net/http"
"fmt"
)
func handler(w http.ResponseWriter, r *http.Request) {
if is_valid_name(r.URL) {
fmt.Fprint(w, "This is a valid name")
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Error 404 - Page not found")
}
}
func main() {
http.HandleFunc("/person/", handler)
http.ListenAndServe(":8080", nil)
}
</code></pre></pre>--Mister--j: <pre><p>Works like a charm. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传