1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goで簡単なWebサーバーを立てる(何の変哲もなく)

Last updated at Posted at 2018-12-08

Goは簡単にWebサーバーを立てられる

標準パッケージのnet/httpを使うと、簡単にWebサーバーを立てられます。最小構成だとこんな感じ。

webServer.go
package main

import (
        "fmt"
        "net/http"
)

/*
        HTTPのリクエストを処理するハンドラです。
        こいつをhttp.HandleFuncでPathにマッピングします。
        funcと引数の名前は決まっていませんが、引数の型は固定です
*/
func Handler(w http.ResponseWriter, r *http.Request) {
        // httpRequestに対する処理を書きます。
        fmt.Fprintf(w, "Hello World\n")
}

func main() {
        // ルートにHandlerをマッピングします。
        http.HandleFunc("/", Handler)
        // ここでWebServer起動
        err := http.ListenAndServe(":80", nil)
        fmt.Println(err)
}

ちょっと汎用的に

Goは関数をreturnできるので、こんな感じでいかがでしょうか。

webSerer.go
package main

import (
        "fmt"
        "net/http"
)

// httpRequestを処理するハンドラfuncを返します。
func GetHandler(fn func(h *http.Request) (string, int)) func(w http.ResponseWriter, r *http.Request) {
        return func(w http.ResponseWriter, r *http.Request) {
                // 渡した任意の関数を実行します。
                msg, status := fn(r)

                if status == http.StatusOK {
                        fmt.Fprintf(w, msg)
                        return
                }

                // ベーシック認証した場合を想定しています。
                if status == http.StatusUnauthorized {
                        w.Header().Set("WWW-Authenticate", `Basic realm="SECRET ZONE"`)
                        fmt.Fprintf(w, msg)
                        return
                }

                http.Error(w, msg, status)
                return
        }
}

// Pathと任意の関数(戻り値:表示文字列, httpステータス)をマッピング
func Map(path string, fn func(h *http.Request) (string, int)) {
        handler := returnHandler(fn)
        http.HandleFunc(path, handler)
}

// Webサーバー起動★
func Start() error {
        err := http.ListenAndServe(":80", nil)
        return err
}

func Hello(r *http.Request) (string, int) {
        return "Hello World\n", http.StatusOK
}

func main() {
        Map("/", Hello)
        err := Start()
        fmt.Println(err)
}

こうすると、表示したい文字列とhttpのステータス(int)を戻り値として持った、任意の関数をPathに対してマッピングすることが出来ます。
httpのステータスとしては、パッケージの中に、http.StatusOk, http.StatusBadRequest, http.Status... というシリーズがあるので、自分で用意する必要はありません。

参考

公式:https://golang.org/pkg/net/http/
ステータス:https://golang.org/src/net/http/status.go

Goは公式のドキュメントが分かりやすくていいですね。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?