LoginSignup
309
249

More than 5 years have passed since last update.

Go言語でhttpサーバーを立ち上げてHello Worldをする

Last updated at Posted at 2014-07-31

Go言語でシンプルにhttpサーバーを立ち上げる場合net/httpを使う。

server1.go
package main

import (
  "fmt"
  "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Hello, World")
}

func main() {
  http.HandleFunc("/", handler) // ハンドラを登録してウェブページを表示させる
  http.ListenAndServe(":8080", nil)
}

ServeHTTPを使う

既存のstructや型に対して、ServeHTTPメソッドを用意することで
http.Handleに登録出来るようにする

package main

import (
  "fmt"
  "net/http"
)

type String string

func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  fmt.Fprint(w, s)
}

func main() {
  http.Handle("/", String("Hello World."))
  http.ListenAndServe("localhost:8000", nil)
}

text/templateを使う

ServeHTTPを既存の型などに定義しなくても
http.ResponseWriter*http.Requestを引数に取る関数を用意すれば
ハンドラとして登録できる。
(こういうのはHandlerインターフェースが正しく設定されていればいい、って説明になるのかな)

Goのテンプレートには text/templatehtml/template がある。
text/templateを使う場合は以下のようになる。

server2.go
package main

import (
  "net/http"
  "text/template"
)

type Page struct { // テンプレート展開用のデータ構造
  Title string
  Count int
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
  page := Page{"Hello World.", 1}  // テンプレート用のデータ
  tmpl, err := template.New("new").Parse("{{.Title}} {{.Count}} count") // テンプレート文字列
  if err != nil {
    panic(err)
  }

  err = tmpl.Execute(w, page) // テンプレートをジェネレート
  if err != nil {
    panic(err)
  }
}

func main() {
  http.HandleFunc("/", viewHandler) // hello
  http.ListenAndServe(":8080", nil)
}

ファイルのテンプレートを使う

テンプレート元の文字列をファイルから読み込みたい場合は
func ParseFiles(filenames ...string) (*Template, error)を使う。

server.go
package main

import (
  "net/http"
  "text/template"
)

type Page struct {
  Title string
  Count int
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
  page := Page{"Hello World.", 1}
  tmpl, err := template.ParseFiles("layout.html") // ParseFilesを使う
  if err != nil {
    panic(err)
  }

  err = tmpl.Execute(w, page)
  if err != nil {
    panic(err)
  }
}

func main() {
  http.HandleFunc("/", viewHandler) // hello
  http.ListenAndServe(":8080", nil)
}

テンプレートファイルを用意する

layout.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>{{.Title}}</title>
  </head>
  <body>
    {{.Title}} {{.Count}} count
  </body>
</html>

実行

$ go run server.go
$ open http://localhost:8080 # Macの場合

ブラウザで “Hello World. 1 count” と表示される

参考

309
249
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
309
249