標準パッケージ   動的なサイト

ホーム   Goチュートリアル
目次


動的なサイト

動的なサイトとは、表示される内容が、実行時に決まるサイトです。

一方、静的なサイトとは、表示される内容が、あらかじめ決まっているサイトです。


dynamicsite.go


package main

import (
	"fmt"
	"net/http"
	"time"
)

func main() {
	// ハンドラーを登録
	http.HandleFunc("/", handler)
	// ターミナルに文字列を表示
	fmt.Println("Enter control + c to exit")
	// サーバーを起動
	http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, `
		<!DOCTYPE html>
		<html lang="ja">
		<body>
			<h1>動的なサイト</h1>
			<p>
			あなたがこのページにアクセスした時刻は、%02d時%02d分です。</p>
		</body>
		</html>
	`, time.Now().Hour(), time.Now().Minute())
}
    


実行結果

テンプレート

動的なサイトで、go ファイルと HTML ファイルを分割して管理するには、テンプレート(html/template)を使います。


ディレクトリ構成

次のようなディレクトリ構成にします。


dynamicsite/
- main.go
- resources/
- - styles/
- - - style.css
- view/
- - index.html
    
ディレクトリ構成、ディレクトリ名、ファイル名は自由に決めて大丈夫です。


main.go


package main

import (
	"html/template"
	"net/http"
	"time"
	"log"
)

func main() {
	// ターミナルに文字列を表示する
	println("Go is running on port 8080 (ctrl-c to quit)")
	// 静的ファイルのディレクトリを指定する
	http.Handle("/resources/", http.StripPrefix("/resources/",http.FileServer(http.Dir("resources/"))))
	// ハンドラーを登録する
	http.HandleFunc("/", handler)
	// 8080 ポートでサーバーを起動する
	http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
	// テンプレートをパースする
	t :=  template.Must(template.ParseFiles("view/index.html"))
	// テンプレートを描画する
	err := t.ExecuteTemplate(w, "index.html", time.Now())
	if err != nil {
		log.Fatal(err)
	}
}
    


index.html


<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="utf-8">
	<title>動的なサイト</title>
	<link rel="stylesheet" href="../resources/styles/style.css">
</head>
<body>
<h1>動的なサイト</h1>
<div align="center"><p>
あなたがこのページにアクセスした時刻は、{{.Hour}}時{{.Minute}}分です。
</p></div>
</body>
</html>
    


style.css


body {
	color: gray;
}

h1 {
    text-align: center;
    font-family: sans-serif;
    font-weight: 100;
    margin-top: 60px;
}
    


起動方法

ターミナルで dynamicsite ディレクトリに移動して、次のように入力します。


// サーバーの起動
go run main.go
Go is running on port 8080 (ctrl-c to quit)

// 終了するには
^C  // control + c
    


表示結果


5994 visits
Posted: Jul. 06, 2019
Update: Jul. 06, 2019

ホーム   Goチュートリアル   目次