Skip to content

Instantly share code, notes, and snippets.

@sekky0905
Last active February 23, 2017 13:49
Show Gist options
  • Save sekky0905/ecc88a699e7c7720d59f11a7a1a7d66b to your computer and use it in GitHub Desktop.
Save sekky0905/ecc88a699e7c7720d59f11a7a1a7d66b to your computer and use it in GitHub Desktop.
Go言語のTemplateパッケージを使い作成したHTMLテンプレートでCSS等の静的ファイルをリンクさせる時の注意 ref: http://qiita.com/Sekky0905/items/fca9d9118ef23bf24791
sample
|_resources <-以下に各種類別静的ファイル(今回はcssのみ)
| |_css
|_view
| |_index.html(テンプレート)
|_main.go
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>テスト</title>
<link rel="stylesheet" type="text/css" href="../resources/css/index.css">
</head>
<body>
<p>名前:{{.Name}}</p>
<p>出身:{{.From}}</p>
</body>
</html>
p {
color:blue;
}
package main
import (
"fmt"
"net/http"
"html/template"
)
func main() {
fmt.Println("The Server runs with http://localhost:8080/")
http.HandleFunc("/", Handler)
http.ListenAndServe(":8080", nil)
}
type Person struct {
Name string
From string
}
func Handler(w http.ResponseWriter, r *http.Request) {
p := Person{
Name:"sekky",
From : "埼玉",
}
tmpl := template.Must(template.ParseFiles("./view/index.html"))
tmpl.Execute(w, p)
}
package main
import (
"fmt"
"net/http"
"html/template"
)
func main() {
fmt.Println("The Server runs with http://localhost:8080/")
// ここで静的ファイルであるCSSを適用
// Handler : 第一引数で与えたパターンに対して、第二引数Handlerを登録
// StripPrefix : 第一引数で与えたURLのパスを取り除いて、第二引数Handlerを発動させる
// FileServer : 、HTTPリクエストに対して、第一引数のrootを起点とするファイルシステムのコンテンツを返すハンドラを返す
// ここでいうrootは、resources
// つまり、resourcesディレクトリ以下の静的ファイル(ここでいうcss/index.css)を探して返す
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources/"))))
http.HandleFunc("/", Handler)
http.ListenAndServe(":8080", nil)
}
type Person struct {
Name string
From string
}
func Handler(w http.ResponseWriter, r *http.Request) {
p := Person{
Name:"sekky",
From : "埼玉",
}
tmpl := template.Must(template.ParseFiles("./view/index.html"))
tmpl.Execute(w, p)
}
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources/"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment