GoのWebFrameworkの goji
が新しくなってたみたいなので、GAEで動くコードを書いてみた。
古い(?)Goji
https://github.com/zenazn/goji
新しいGoji
https://github.com/goji/goji
かなりコード変わっているので互換性はないっぽい。今回は新しいGojiを使ってコードを書いてみる。
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"goji.io"
"goji.io/pat"
"golang.org/x/net/context"
)
func init() {
mux := goji.NewMux()
mux.HandleFuncC(pat.Get("/"), index)
mux.HandleFuncC(pat.Get("/hello/:name"), hello)
mux.HandleFuncC(pat.Get("/article"), article)
http.Handle("/", mux)
}
func index(c context.Context, w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "index page")
}
func hello(c context.Context, w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", pat.Param(c, "name"))
}
type Article struct {
Title string `json:"title"`
Content string `json:"content"`
}
func article(c context.Context, w http.ResponseWriter, r *http.Request) {
article := Article{
Title: "title",
Content: "hello world",
}
response, _ := json.Marshal(article)
io.WriteString(w, string(response))
}
下記コマンドで実行する。
$ goapp serve
こんな感じで動く。
ログもこんな感じ。
今回書いたサンプルコードはこちらにおいておきます。
https://github.com/funnythingz/try-gae-go