I'm trying to display a static page with GO.
GO:
package main
import "net/http"
func main() {
fs := http.FileServer(http.Dir("static/home"))
http.Handle("/", fs)
http.ListenAndServe(":4747", nil)
}
Directory:
Project
/static
home.html
edit.html
project.go
When I run it, the web page displays the links to edit.html and home.html instead of displaying the static page from home.html. What am I doing wrong. Is this the best way to serve files? I know there are other ways eg. from the html/templates package but I'm not sure what the difference is and when to use each of these methods. Thanks!
func main() {
http.Handle("/", http.FileServer(http.Dir("static")))
http.ListenAndServe(":4747", nil)
}
You don't need static/home
, just static
.
FileServer is using directory listing and since you don't have an index.html
in /static
, the directory content is shown instead.
A quick fix would be to just rename home.html
to index.html
. This would allow you to access index.html
through http://localhost:4747/
and edit.html
with http://localhost:4747/edit.html
.
There's no need to use html/template
if you only need to serve static files.
But a clean solution depends on what you are actually trying to do.
If you're only interested in writing a simple server that serves static content and not just as a learning experience I'd take a look at Martini (http://martini.codegangsta.io/).
The quintessential Martini app to serve static files from a folder named 'public' would be:
package main
import (
"github.com/go-martini/martini"
)
func main() {
m := martini.Classic()
m.Run()
}
to add a new static folder called 'static' to the list of static folders searched for content is also simple:
package main
import (
"github.com/go-martini/martini"
)
func main() {
m := martini.Classic()
m.Use(martini.Static("static")) // serve from the "static" directory as well
m.Run()
}
Martini provides lots more functionality as well, such as session, template rendering, route handlers etc...
We're using Martini in production here and have been more than happy with it and it's surrounding infrastructure.