<p>I'm running a website with a very basic webserver</p>
<pre><code>http.Handle("/", http.FileServer(http.Dir("static")))
http.Handle("/ws", websocket.Handler(EchoServer))
log.Println("Listening at 3000...")
if err := http.ListenAndServe(":3000", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
</code></pre>
<p>I need access to http.responseWriter in particular for the IP's of connecting client. I thought about using http.HandlerFunc, but nothing is served when I visit localhost:3000.</p>
<pre><code>http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.Dir("static"))
})
http.Handle("/ws", websocket.Handler(EchoServer))
log.Println("Listening at 3000...")
if err := http.ListenAndServe(":3000", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
</code></pre>
<p>How can I server static files and still have access to http.request?
Thanks!</p>
<hr/>**评论:**<br/><br/>patrickdappollonio: <pre><p>You can change the code inside the <code>/</code> handler to be:</p>
<pre><code>f, err := os.Open(r.URL.Path)
if err != nil {
if os.IsNotExists(err) {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.ServeContent(w, r, info.Name(), info.ModTime(), f)
f.Close()
</code></pre>
<p>It will require some extra code check just to know stuff like if the file exists, or if the path is a correct one and so on, but that way, you can still serve your static asset.</p>
<p>The reason why you're not getting is because you're using <code>http.FileServer</code> which is a full featured file server, which is a handler by itself, but not getting called as a handler. It's meant to be passed to a function that can execute handlers.</p></pre>patrickdappollonio: <pre><p>I think you can also use <code>http.ServeFile</code> by changing all the above code to:</p>
<pre><code>http.ServeFile(w, r, r.URL.Path)
</code></pre>
<p>This is way less verbose but the above code can help you out understanding the overall flow.</p></pre>julianxxxx: <pre><p>Thanks but your solution doesn't quite work. Not sure why. This solution worked for me</p>
<pre><code>func homeHandler(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.Dir("static")).ServeHTTP(w, r)
if r.URL.Path == "/" {
r.RemoteAddr = strings.Replace(r.RemoteAddr, "[::1]", "localhost", -1)
log.Printf("Request of %v from %v", r.URL.Path, r.RemoteAddr)
}
}
func main() {
http.HandleFunc("/", homeHandler)
http.Handle("/ws", websocket.Handler(EchoServer))
log.Println("Serving to :3000")
log.Fatal(http.ListenAndServe(":3000", nil))
}
</code></pre></pre>patrickdappollonio: <pre><p>I think it's because in your code you're serving the "static" folder, whereas in my code I'm serving <code>r.URL.Path</code></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传