LoginSignup
11
13

More than 5 years have passed since last update.

GoのWebフレームワークのGoji (goji.io) をGAEで動かす

Last updated at Posted at 2016-04-23

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

こんな感じで動く。

image

image

image

image

ログもこんな感じ。

image

今回書いたサンプルコードはこちらにおいておきます。
https://github.com/funnythingz/try-gae-go

11
13
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
11
13