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というファイルを用意しているものとします
■サンプルコード
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 の内容が返される