LoginSignup
24
21

More than 5 years have passed since last update.

Go言語でシンプルなWebAPIサーバーを実装する

Posted at

Go言語 初心者向けハンズオン用資料です。
https://techdo.connpass.com/event/100306/

簡単なWebサーバーの書き方と動かし方を説明します。

Go言語ではパッケージと呼ばれる様々なライブラリを取り込んで使うことのできる機能が備わっています。
パッケージには言語に組み込まれている内部パッケージ、有志によって開発された外部パッケージがあります。

  • net/http(内部パッケージ)
  • julienschmidt/httprouter(外部パッケージ)

1. 外部パッケージを導入する

$ go get github.com/julienschmidt/httprouter

2. Webサーバーとして動くコードを書く

main.go

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

// /Hello/:langにハンドルされているHello関数
func Hello(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
    lang := p.ByName("lang") // langパラメーターを取得する
    fmt.Fprintf(w, lang)     // レスポンスに値を書き込む
}

// /ExampleにハンドルされているExample関数
func Example(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
    defer r.Body.Close() // Example関数が終了する時に実行されるdeferステートメント

    // リクエストボディを読み取る
    bodyBytes, err := ioutil.ReadAll(r.Body)
    if err != nil {
        // リクエストボディの読み取りに失敗した => 400 Bad Requestエラー
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // JSONパラメーターを構造体にする為の定義
    type ExampleParameter struct {
        ID   int    `json:"id"`
        Name string `json:"name"`
    }
    var param ExampleParameter

    // ExampleParameter構造体に変換
    err = json.Unmarshal(bodyBytes, &param)
    if err != nil {
        // JSONパラメーターを構造体への変換に失敗した => 400 Bad Requestエラー
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // 構造体に変換したExampleParameterを文字列にしてレスポンスに書き込む
    fmt.Fprintf(w, fmt.Sprintf("%+v\n", param))
}

func main() {
    router := httprouter.New() // HTTPルーターを初期化

    // /HelloにGETリクエストがあったらHello関数にハンドルする
    // :langはパラメーターとして扱われる
    router.GET("/Hello/:lang", Hello)

    // /ExampleにPOSTリクエストがあったらExample関数にハンドルする
    router.POST("/Example", Example)

    // Webサーバーを8080ポートで立ち上げる
    err := http.ListenAndServe(":8080", router)
    if err != nil {
        log.Fatal(err)
    }
}

3. Webサーバーを起動する

$ go run main.go

4. Webサーバーにアクセスする

ブラウザでhttp://localhost:8080/Hello/golangにアクセスしてみましょう。
POSTリクエストはcurlコマンドで叩いてみましょう。

$ curl -XPOST -d "{\"id\": 1, \"name\": \"yukpiz\"}" http://localhost:8080/Example
24
21
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
24
21