Go Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it…

In this recipe, we are going to create a file server that will serve static resources from the filesystem. Perform the following steps:

  1. Create main.css inside a static/css directory, as follows:
$ mkdir static && cd static && mkdir css && cd css && touch main.css
  1. Copy the following content to main.css:
body {color: #00008B}
  1. Create serve-static-files.go, where we will create FileServer, which will serve resources from the static/css directory present on the filesystem for all URL patterns with  /static, as follows:
package main
import
(
"fmt"
"html/template"
"log"
"net/http"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type Person struct
{
Name string
Age string
}
func renderTemplate(w http.ResponseWriter, r *http.Request)
{
person := Person{Id: "1", Name: "Foo"}
parsedTemplate, _ := template.ParseFiles("templates/
first-template.html")
err := parsedTemplate.Execute(w, person)
if err != nil
{
log.Printf("Error occurred while executing the template
or writing its output : ", err)
return
}
}
func main()
{
fileServer := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fileServer))
http.HandleFunc("/", renderTemplate)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
  1. Update first-template.html (created in our previous recipe) to include main.css from the static/css directory:
<html>
<head>
<meta charset="utf-8">
<title>First Template</title>
<link rel="stylesheet" href="/static/css/main.css">
</head>
<body>
<h1>Hello {{.Name}}!</h1>
Your Id is {{.Id}}
</body>
</html>

With everything in place, the directory structure should look like the following:

  1. Run the program with the following command:
$ go run serve-static-files.go