金融と工学のあいだ

興味関心に関するメモ(機械学習、検索エンジン、プログラミングなど)

golang設定

やりたいこと

設定のメモ

wantedlyの資料

やっぱり1から書いてみる

まずは簡単にサーバを立ててみよう

ファイル構成はこんな感じ

$ tree ../
../
└── goweb
    ├── LICENSE
    ├── README.md
    └── main.go

main.goの中身はこんな感じ。

package main

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

実行してみた

$ go run main.go

ブラウザから見た感じ f:id:kumechann:20170812002319p:plain

routerを使ってみた

  • routerは"github.com/gorilla/mux"と言うものが有名らしい
  • $ go getすると勝手に関連モジュールがdownloadされる
package main

import (
    "fmt"
    "net/http"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    // 単純なハンドラ
    r.HandleFunc("/", Index)

    // パスに変数を埋め込み
    r.HandleFunc("/users", UserIndex)

    // パスに変数を埋め込み
    r.HandleFunc("/users/{userId}", UserIndexId)

    // パス変数で正規表現を使用

    // マッチするパスがない場合のハンドラ
    r.NotFoundHandler = http.HandlerFunc(NotFoundHandler)

    // http://localhost:8080 でサービスを行う
    http.ListenAndServe(":8080", r)
}

func Index(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Index!\n"))
}

func UserIndex(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("UserIndex!\n"))
}

func UserIndexId(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    fmt.Fprintf(w, "%s user index\n", vars["userId"])
}

func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Gorilla!\nNot Found 404\n"))
}

JSONを返却する

user.goにuser型の定義を書く

package main

type User struct {
    Id      string
    Name    string
}

type Users []User

UserIndexをJSONを返すように書き直す

func UserIndex(w http.ResponseWriter, r *http.Request) {
    users := Users{
        User{Id: "00000001", Name: "keisuke"},
        User{Id: "00000002", Name: "yusuke"},
    }
    json.NewEncoder(w).Encode(users)
}

最終型

github.com

  • つけた機能
    • メモリ上に配置した仮想DB
    • データのPOST機能
    • error機能