Go Golang to serve a specific html file

Maybe using a custom http.HandlerFunc would be easier:

Except in your case, your func would be the http.ServeFile one, for serving just one file.

See for instance “Go Web Applications: Serving Static Files”:

Add the following below your home handler (see below):

http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
   // do NOT do this. (see below)
    http.ServeFile(w, r, r.URL.Path[1:])
})

This is using the net/http package’s ServeFile function to serve our content.
Effectively anything that makes a request starting with the /static/ path will be handled by this function.
One thing I found I had to do in order for the request to be handled correctly was trim the leading ‘/’ using:

r.URL.Path[1:]

Actually, do not do that.
This won’t be possible in Go 1.6, as sztanpet comments, with commit 9b67a5d:

If the provided file or directory name is a relative path, it is
interpreted relative to the current directory and may ascend to parent
directories
.
If the provided name is constructed from user input, it should be sanitized before calling ServeFile.
As a precaution, ServeFile will reject requests where r.URL.Path contains a “..” path element.

That will protect against the following “url”:

/../file
/..
/../
/../foo
/..\\foo
/file/a
/file/a..
/file/a/..
/file/a\\..

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)