今日はgolangでcssファイルを読み込む方法について紹介します。
以下の記事で作成したwebコンテナのindex.htmlからcssファイルを利用する方法について紹介します。
GoとMongoDBのコンテナでフロントとバックエンドを分けてみる
- cssファイルを作成する
- htmlファイルを編集する
- main.goを編集する
- アプリケーションを起動して確認する
cssファイルを作成する
オレンジ色のボタンのフォーマットをcssファイル(button.css)で作成します。cssファイルが主役ではないので、説明は省略します。
.btn-push { display: inline-block; width: 180px; text-align: center; background-color: #ffa300; font-size: 16px; color: #FFF; text-decoration: none; font-weight: bold; padding: 10px 24px; border-radius: 4px; border-bottom: 4px solid #d37800; } .btn-push:active { transform: translateY(4px); border-bottom: none; }
以下のディレクトリに配置します。
$ tree web web ├── Dockerfile └── src ├── main.go ├── public │ └── css │ └── button.css └── templates ├── index.html └── layout.html
htmlファイルを編集する
button.cssファイルを読み込んで、配列データにボタンフォーマットを適用するindex.htmlを作成します。
linkタグでcssをリンクしている訳ですが、ファイルパスが/static/css/button.css
であることに注意してください。配置したパスと異なっています。これはmain.goの記述で変更することができます。今回は分かりやすいようにパスを変えてみました。
{{ define "content" }} <link href="/static/css/button.css" rel="stylesheet"> {{ range .Categories }} <a href="index.html" class="btn-push" style="margin: 10px 20px">{{ .Name }}</a> {{ end }} {{ end }}
main.goを編集する
webコンテナのmain.goを以下に編集します。気づいた方もいらっしゃると思いますが、gorilla/muxをやめました。ビルドする度にパッケージをインストールするのを省略するためです。
大きな変更点は、http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("public/"))))
を追加した点です。publicディレクトリ配下の静的ファイルを読み込んで、/static/で公開しています。従って、htmlファイルでcssをリンクするときは、公開するパスになります。
package main import ( "encoding/json" "fmt" "log" "net/http" "io/ioutil" "os" "html/template" ) type category struct { Categories []struct{ Name string `json:"name"` }`json:"categories"` } func main() { //public配下の静的ファイルを読み込み http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("public/")))) //ハンドラーにindexを登録 http.Handle("/", index) //サーバー起動 if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal("ListenAndServe:", nil) } } var index = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { url := "http://searcher:8082/public" req, _ := http.NewRequest("GET", url, nil) client := new(http.Client) resp, _ := client.Do(req) defer resp.Body.Close() byteArray, _ := ioutil.ReadAll(resp.Body) var categories category if err := json.Unmarshal(byteArray, &categories); err != nil { log.Fatal(err) os.Exit(1) } generateHTML(w, categories, "layout", "index") }) func generateHTML(writer http.ResponseWriter, data interface{}, filenames ...string) { var files []string for _, file := range filenames { files = append(files, fmt.Sprintf("templates/%s.html", file)) } templates := template.Must(template.ParseFiles(files...)) templates.ExecuteTemplate(writer, "layout", data) }
アプリケーションを起動して確認する
ここからアプリケーションを起動します。
1. Dockerfileを編集する
gorilla/muxのパッケージインストール行を削除しています。
FROM golang:latest # コンテナ作業ディレクトリの変更 WORKDIR /go/src/web # ホストOSの ./src の中身を作業ディレクトリにコピー COPY ./src . RUN go build -o web # ウェブアプリケーション実行コマンドの実行 CMD ["./web"]
2. コンテナイメージを作成する
$ docker build -t web:latest web/
3. コンテナを起動する
docker-composeコマンドでアプリケーションを起動します。searcherとdbのイメージはGoとMongoDBのコンテナでフロントとバックエンドを分けてみるを参照してください。
$ docker-compose up -d Creating network "wishy_default" with the default driver Creating db ... done Creating searcher ... done Creating web ... done
4. ブラウザで確認する
http://localhost:8080をブラウザに直接入力すると、以下のように配列データがボタンとして表示されます。

以上です!