Go言語ではnet/http
を利用することでHTTPサーバを立てることができまが、Gin
といったWebアプリ用のフレームワークも存在しています。
事前準備
以下を実行してGin
のパッケージ取得を行います
go get github.com/gin-gonic/gin
とりあえずHello World
以下 Hello World の文字列を返す例です。
Engine.GET
により、ハンドリング対象のパスとハンドラを登録します。
■サンプルコード
package main import ( "log" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/hello", func(ctx *gin.Context) { ctx.String(200, "Hello World") }) if err := router.Run(":8686"); err != nil { log.Fatal("Server Run Failed.: ", err) } }
■実行結果
http://localhost:8686/hello
にアクセスすると以下の結果が出力されます
Hello World
静的ページを返す
URLへのアクセスに対して静的ページを返す場合は、router.StaticFS
等を利用します。
以下サンプルでは、staticディレクトリにindex.htmlとuser.htmlというファイルを用意しているものとします
■サンプルコード
package main import ( "log" "net/http" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.StaticFS("/web", http.Dir("static")) if err := router.Run(":8686"); err != nil { log.Fatal("Server Run Failed.: ", err) } }
■実行結果
http://localhost:8686/web/
に アクセスすると staticディレクトリのindex.html の内容が返されるhttp://localhost:8686/web/user.html
に アクセスすると staticディレクトリのuser.html の内容が返される