Hi all!
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:
http.HandleFunc("../client", helloWorldHandler)
But the path does not seem to work. My directory tree looks something like this:
-client
--index.html
-server
--server.go
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?
Thank you kindly!
评论:
ematap:
SebaTheOneAndOnly: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:
https://golang.org/pkg/net/http/#FileServer
You also probably want to use Handle instead of HandleFunc here
kokster_:Thank you for that!
SebaTheOneAndOnly:Hi there!
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 http://example.com
Then, say if your website has a blog page at http://example.com/blog
then
/blog
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 thishttp.HandleFunc("/blog", blogHandler) // this handler will get whenever someone visits http://www.example.com/blog
In order to match the root path (
http://www.example.com
), you can use this selector defined in the examplehttp.HandleFunc("/", rootHandler)
In order to send a request to "/client/index.html", you can do that by following the example here: https://golang.org/src/net/http/fs.go#L709
qu33ksilver:I see. Thank you kindly!
SebaTheOneAndOnly:This should work for you -
package main import ( "net/http" ) func main() { http.Handle("/client/", http.StripPrefix("/client/", http.FileServer(http.Dir(".")))) }
It's not working, but don't worry. Thank you for your help!
