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

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


静的なサイト

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

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


ディレクトリ構成

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


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


main.go


package main

import (
	"net/http"
)

func main() {
	// ディレクトリの指定
	fs := http.FileServer(http.Dir("static"))
	// "/" にアクセスしたら static ディレクトリのコンテンツを表示する
	http.Handle("/", fs)
	// ターミナルに文字列を表示する
	println("Enter control + c to exit")
	// 8080 ポートでサーバーを起動する
	http.ListenAndServe(":8080", nil)
}
    


index.html


<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="utf-8">
	<title>静的なサイト</title>
	<link rel="stylesheet" href="/styles/style.css">
</head>
<body>
	<h1>静的なサイト</h1>
	
	<div align="center">
	<p>
	このページは、静的なページ(static page)です。
	</p>
	</div>
</body>
</html>
    


style.css


body {
	color: gray;
}

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


起動方法

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


// サーバーの起動
go run main.go
Enter control + c to exit

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


表示結果


5987 visits
Posted: Jul. 05, 2019
Update: Jul. 06, 2019

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