- Go Web Development Cookbook
- Arpit Aggarwal
- 234字
- 2021-08-27 19:01:16
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:
- Create main.css inside a static/css directory, as follows:
$ mkdir static && cd static && mkdir css && cd css && touch main.css
- Copy the following content to main.css:
body {color: #00008B}
- 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
}
}
- 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:

- Run the program with the following command:
$ go run serve-static-files.go
推薦閱讀
- EJB 3.1從入門到精通
- 智慧城市:大數(shù)據(jù)、互聯(lián)網(wǎng)時(shí)代的城市治理(第4版)
- 數(shù)據(jù)通信網(wǎng)絡(luò)實(shí)踐:基礎(chǔ)知識(shí)與交換機(jī)技術(shù)
- Twilio Cookbook
- 電子政務(wù)效益的經(jīng)濟(jì)分析與評(píng)價(jià)
- 物聯(lián)網(wǎng)之霧:基于霧計(jì)算的智能硬件快速反應(yīng)與安全控制
- 網(wǎng)絡(luò)基礎(chǔ)與網(wǎng)絡(luò)管理項(xiàng)目化教程
- 網(wǎng)管工具使用與技巧大全
- Echo Quick Start Guide
- 物聯(lián)網(wǎng)工程導(dǎo)論(第3版)
- Learning Node.js Development
- RestKit for iOS
- Building Microservices with Spring
- ElasticSearch Server
- 互聯(lián)網(wǎng)戰(zhàn)略變革與未來