LoginSignup
37
29

More than 5 years have passed since last update.

Goでwebサーバーを立てる3ステップ

Last updated at Posted at 2018-12-09

Goでローカルサーバーを立てる

Goでは標準でnet/httpパッケージが用意されており、少ないコードでwebサーバーを立てることができます。画像のように、ローカルで簡単なCSSをつけた静的コンテンツを表示させてみたいと思います。

68747470733a2f2f71696974612d696d6167652d73746f72652e73332e616d617a6f6e6177732e636f6d2f302f3236303832342f62666564383163322d336632362d356362372d306230642d6139613835633565363562392e706e67.png

1.ディレクトリを作る

以下の構成でディレクトリを作っていきます。

$HOME/go_tutorial
- main.go
- static/
- - index.html
- - styles/
- - - style.css

ホームディレクトリ以下にに「go_tutorial」ディレクトリを作り、メインのコードを書くmain.goとコンテンツを入れるstaticディレクトリを配置します。

$ mkdir go_tutorial
$ cd go_tutorial
$ touch main.go
$ mkdir -p static/stylesheets
$ touch static/index.html static/stylesheets/styles.css

2.main.goとhtml・cssを用意する

main.go
package main

import (
    "log"
    "net/http"
)

func main() {
    //ディレクトリを指定する
    fs := http.FileServer(http.Dir("static"))
    //ルーティング設定。"/"というアクセスがきたらstaticディレクトリのコンテンツを表示させる
    http.Handle("/", fs)

    log.Println("Listening...")
    // 3000ポートでサーバーを立ち上げる
    http.ListenAndServe(":3000", nil)
}

~/static/index.html
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>A static page</title>
  <link rel="stylesheet" href="/stylesheets/styles.css">
</head>
<body>
  <h1>Hellooooooooooooo</h1>
</body>
</html>
~/static/stylesheets/styles.css
body {color: #c0392b}

3.サーバーを立ち上げる

コードがかけたらmain.goを動かします。

$ go run main.go

その上で http://localhost:3000/
にアクセスすればコンテンツが表示されます。

ServeMuxとは何か

Goのhttpパッケージの文脈で、Servemuxという用語がよく出てきます。
・ServeMuxとは、HTTPリクエストに対するルーターです。URLのパターンにマッチするハンドラーを呼び出します。
・Muxというのはmultiplexor(直訳すると、「多重装置」)の略で、色々なパターンのURLリクエストに対して対応するハンドラーに振り分けます。
・ハンドラーはHTTPレスポンスヘッダーとボディを返します。
・DefalutServeMuxという用語もよく登場しますが、これはHTTPパッケージを使うときに最初に定義されているServemuxのことです。

参考

Creating simple webserver with golang
https://tutorialedge.net/golang/creating-simple-web-server-with-golang/
Serving static sites with Go
https://www.alexedwards.net/blog/serving-static-sites-with-go
Understanding Go Standard Http Libraries : ServeMux, Handler, Handle and HandleFunc
https://rickyanto.com/understanding-go-standard-http-libraries-servemux-handler-handle-and-handlefunc/
A Recap of Request Handling in Go
https://www.alexedwards.net/blog/a-recap-of-request-handling

37
29
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
29