Serving static files
Almost any web application needs to serve static files. The serving of JavaScript files, static HTML pages, or CSS style sheets could be easily achieved with the use of the standard library. This recipe will show how.
How to do it...
- Open the console and create the folder
chapter09/recipe07
. - Navigate to the directory.
- Create the file
welcome.txt
with the following content:
Hi, Go is awesome!
- Create the folder
html
, navigate to it and create the filepage.html
with the following content:
<html> <body> Hi, I'm HTML body for index.html! </body> </html>
- Create the
static.go
file with the following content:
package main import ( "net/http" ) func main() { fileSrv := http.FileServer(http.Dir("html")) fileSrv = http.StripPrefix("/html", fileSrv) http.HandleFunc("/welcome", serveWelcome) http.Handle("/html/", fileSrv) ...