官术网_书友最值得收藏!

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
主站蜘蛛池模板: 建平县| 平利县| 英山县| 高邮市| 应城市| 林芝县| 吴旗县| 太保市| 霍邱县| 屏山县| 青铜峡市| 万安县| 和静县| 乌兰察布市| 黎川县| 郓城县| 教育| 北川| 松潘县| 筠连县| 武夷山市| 全南县| 常州市| 梅河口市| 晋中市| 嘉峪关市| 荣昌县| 怀宁县| 岚皋县| 太康县| 临江市| 通榆县| 吴江市| 芦山县| 东辽县| 隆子县| 太仆寺旗| 安岳县| 准格尔旗| 绥宁县| 康乐县|