<p>Hi all!</p>
<p>So what I am trying to do is create a HTTP server with Golang. I am a beginner by the way!
What I have written so far is this:</p>
<p>http.HandleFunc("../client", helloWorldHandler)</p>
<p>But the path does not seem to work. My directory tree looks something like this:</p>
<p>-client</p>
<p>--index.html</p>
<p>-server</p>
<p>--server.go</p>
<p>And I am trying to make my main path to send to /client/index.html but it is not working out.. Any idea what I should do? </p>
<p>Thank you kindly! </p>
<hr/>**评论:**<br/><br/>ematap: <pre><p>The first argument of Handle and HandleFunc is the prefix of the path of the request that your server received. The second argument is how you handle the response. In your case, you probably want to make your second argument with http.FileServer:</p>
<p><a href="https://golang.org/pkg/net/http/#FileServer" rel="nofollow">https://golang.org/pkg/net/http/#FileServer</a></p>
<p>You also probably want to use Handle instead of HandleFunc here</p></pre>SebaTheOneAndOnly: <pre><p>Thank you for that! </p></pre>kokster_: <pre><p>Hi there! </p>
<p>I see what you did there. The HandlerFunc takes in a path as its first argument. This path is the path of the URL that must be handled by this function. For example, say you have a website <a href="http://example.com" rel="nofollow">http://example.com</a></p>
<p>Then, say if your website has a blog page at <a href="http://example.com/blog" rel="nofollow">http://example.com/blog</a> </p>
<p>then <code>/blog</code> is the path in this case. Therefore, in order to write a handler for that path, you'd write a handler func that looks like this</p>
<pre><code>http.HandleFunc("/blog", blogHandler) // this handler will get whenever someone visits http://www.example.com/blog
</code></pre>
<p>In order to match the root path (<code>http://www.example.com</code>), you can use this selector defined in the example</p>
<pre><code>http.HandleFunc("/", rootHandler)
</code></pre>
<p>In order to send a request to "/client/index.html", you can do that by following the example here: <a href="https://golang.org/src/net/http/fs.go#L709" rel="nofollow">https://golang.org/src/net/http/fs.go#L709</a></p></pre>SebaTheOneAndOnly: <pre><p>I see. Thank you kindly! </p></pre>qu33ksilver: <pre><p>This should work for you - </p>
<pre><code>package main
import (
"net/http"
)
func main() {
http.Handle("/client/", http.StripPrefix("/client/", http.FileServer(http.Dir("."))))
}
</code></pre></pre>SebaTheOneAndOnly: <pre><p>It's not working, but don't worry. Thank you for your help! </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传