Serving static files on the file system
Not all files served by web applications are dynamically generated. JavaScript files, cascading stylesheets, and some HTML pages are usually served verbatim. This section shows several methods to serve such files.
How to do it...
There are several ways a static file can be served via HTTP:
- To serve all static files under a directory, use
http.FileServer
to create a handler:fileHandler := http.FileServer(http.Dir("/var/www")) server:=http.Server{ Addr: addr, Handler: fileHandler, } http.ListenAndServe()
The above snippet will serve the files under
/var/www
at the root path. That is, aGET /index.html
request will serve the/var/www/index.html
file withContent-Type: text/html
. Similarly, aGET /css/styles.css
will serve/var/www/css/styles.css
withContent-Type: text/css
. - To serve all static files under a directory but with a different URL path prefix, use
http.StripPrefix
:fileHandler := http.StripPrefix...