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.FileServerto 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/wwwat the root path. That is, aGET /index.htmlrequest will serve the/var/www/index.htmlfile withContent-Type: text/html. Similarly, aGET /css/styles.csswill serve/var/www/css/styles.csswithContent-Type: text/css. - To serve all static files under a directory but with a different URL path prefix, use
http.StripPrefix:fileHandler := http.StripPrefix...