覚えたら書く

IT関係のデベロッパとして日々覚えたことを書き残したいです。twitter: @yyoshikaw

Go言語 - HTTPサーバでHello World

Go言語ではnet/httpを利用することでHTTPサーバを立てることができます。

とりあえず今回はお試しな感じでHTTPサーバを立ててみます


とりあえずHello World

以下 Hello World の文字列を返す例です。

http.HandleFuncにより、ハンドリング対象のパスとハンドラを登録します。その後にhttp.ListenAndServeでHTTPサーバを起動します

■サンプルコード

package main

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

func main() {

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

        // ポート = 8686
    if err := http.ListenAndServe(":8686", nil); err != nil {
        log.Fatal("ListenAndServe failed.", err)
    }
}


■実行結果

http://localhost:8686/helloにアクセスすると以下の結果が出力されます

Hello World


静的ページを返す

URLへのアクセスに対して静的ページを返す場合は、http.FileServer を利用します。

以下サンプルでは、staticディレクトリにindex.htmlとuser.htmlというファイルを用意しているものとします

f:id:nini_y:20170519174645p:plain


■サンプルコード

package main

import (
    "log"
    "net/http"
)

func main() {
    http.Handle("/", http.FileServer(http.Dir("static")))

    if err := http.ListenAndServe(":8686", nil); err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

■実行結果

  • http://localhost:8686/ に アクセスすると staticディレクトリのindex.html の内容が返される
  • http://localhost:8686/user.html に アクセスすると staticディレクトリのuser.html の内容が返される


URLからprefix部分を取り除いてハンドリングする場合

アクセスされたURLのPrefixを除いて、ハンドリングする場合は http.StripPrefix を利用します

■サンプルコード

package main

import (
    "log"
    "net/http"
)

func main() {
    
    // アクセスされたURLから /web 部分を取り除いてハンドリングする
    http.Handle("/web", http.StripPrefix("/web", http.FileServer(http.Dir("static"))))

    if err := http.ListenAndServe(":8686", nil); err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

■実行結果

  • http://localhost:8686/web/ に アクセスすると staticディレクトリのindex.html の内容が返される
  • http://localhost:8686/web/user.html に アクセスすると staticディレクトリのuser.html の内容が返される



関連エントリ