覚えたら書く

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

Go言語 - Ginを使ってHello World

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というファイルを用意しているものとします

f:id:nini_y:20170519185348p:plain


■サンプルコード

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 の内容が返される



関連エントリ