Go言語で作る webアプリ@gocon 2013 spring
- 4. アジェンダ
● Webサーバを作ろう
○ net/httpパッケージ
● RESTful APIを作ろう
○ RESTful APIとは?
○ gowebの使い方
● おまけ
- 7. Go言語でhttpリクエストをハンドル
http.Server http.Handler
80番ポート
ListenAndServe ハンドル
@80ポート
ブラウザ
クライアントサイド サーバサイド
- 8. http.Server型
type Server struct {
Addr string
Handler Handler
ReadTimeout time.Duration
WriteTimeout time.Duration
MaxHeaderBytes int
TLSConfig *tls.Config
}
- 9. http.Server型
● type Server struct
○ func (srv *Server) ListenAndServe() error
○ func (srv *Server) ListenAndServeTLS(certFile,
keyFile string) error
○ func (srv *Server) Serve(l net.Listener) error
- 11. 複数のハンドラを設定する
http.Handler
aa
/a
http.Handler
b
http.Server http.ServeMux /bb
ListenAndServe ハンドル
@80ポート /zzz
http.Handler
- 12. http.ServeMux型
type struct ServeMux{}
// 指定したパタンでハンドラを登録
func (mux *ServeMux) Handle(pattern string,
handler Handler)
// 指定したパタンでハンドラ関数を登録
func (mux *ServeMux) HandleFunc(pattern
string, handler func(ResponseWriter, *Request)
// http.Handlerの実装
func (mux *ServeMux) ServeHTTP(w
ResponseWriter, r *Request)
- 16. 簡単な例:hello, http!!
func main() {
f := func(w http.ResponseWriter, r *http.
Request) {
fmt.Fprintf(w, "hello, http!!")
}
http.HandleFunc("/", f)
http.ListenAndServe(":8080", nil)
}
https://github.com/golang-samples/http/tree/master/handlefunc
- 17. 簡単な例:静的ファイル
func main() {
// static以下のファイルを提供
http.Handle("/", http.FileServer(http.Dir("static")))
http.ListenAndServe(":8080", nil)
}
https://github.com/golang-samples/http/tree/master/fileserv
- 20. RESTful APIとは?
● 明示的にHTTPメソッドを使う
○ POST, GET, PUT, DELETE
○ CRUDと対応
● ステートレスにする
○ 状態を保存しない
● ディレクトリ構造に似たURI
○ /api/persons/10
● XML、JSONなどを転送する
○ リクエストやレスポンスにXMLやJSONを使用
- 22. GoWebってなに?
● RESTful APIを作るためのライブラリ
○ https://github.com/stretchrcom/goweb
● 細かいルーティング管理できる
● Controllerを作り、POST, GET, PUT, DELETE
などの単位でハンドリング
● JSONやXMLをリクエストから作れる
● レスポンスを簡単に作れる
○ 良く使うステータスコード
○ JSONやXML
- 23. GoWebの構造
DefaultRouteManager
:HttpHandler :RouteManager
:Controller
ServeHTTP GetMathingRoute()
routes
loop:routes
if:route.DoesMatchContext
route.Controller.HandleRequest()
- 24. GoWebの簡単な使い方
func main() {
handler := func(c *goweb.Context) {
name := c.PathParams["name"]
animal := c.PathParams["animal"]
fmt.Fprintf(c.ResponseWriter, "Hey %s,
your favorite animal is a %s", name, animal)
}
goweb.MapFunc("/people/{name}/animals/
{animal}", handler)
goweb.ListenAndServe(":8080")
}
https://github.com/golang-samples/goweb/tree/master/mapfunc
- 25. GoWebの簡単な使い方 RESTful API
// REST用のコントローラー
type MyController struct {}
HTTPメソッド URI例 実装するメソッド
POST /api/ RestCreater.Create
GET /api/ RestManyReader.ReadMany
GET /api/123 RestReader.Read
PUT /api/ RestManyUpdater.UpdateMany
PUT /api/123 RestUpdater.Update
DELETE /api/ RestManyDeleter.DeleteMany
DELETE /api/123 RestDeleter.Delete
※必要なものだけ、実装する
- 26. GoWebの簡単な使い方 RESTful API
// POSTをハンドリングする
func (cr *MyController) Create(cx
*goweb.Context) {
fmt.Fprintf(cx.ResponseWriter,
"Create new resource")
}
- 27. GoWebの簡単な使い方 RESTful API
// GETをハンドリング(id指定)
func (cr *MyController) Read(id string, cx *goweb.
Context) {
fmt.Fprintf(cx.ResponseWriter, "Read
resource %s", id)
}
// GETをハンドリング(id指定なし)
func (cr *MyController) ReadMany(cx *goweb.
Context) {
fmt.Fprintf(cx.ResponseWriter, "Read many
resources")
}
- 28. GoWebの簡単な使い方 RESTful API
// PUTをハンドリング(id指定)
func (cr *MyController) Update(id string, cx
*goweb.Context) {
fmt.Fprintf(cx.ResponseWriter, "Update
resource %s", id)
}
// PUTをハンドリング(id指定なし)
func (cr *MyController) UpdateMany(cx *goweb.
Context) {
fmt.Fprintf(cx.ResponseWriter, "Update
many resources")
}
- 29. GoWebの簡単な使い方 RESTful API
// DELETEをハンドリング(id指定)
func (cr *MyController) Delete(id string, cx
*goweb.Context) {
fmt.Fprintf(cx.ResponseWriter, "Delete
resource %s", id)
}
// DELETEをハンドリング(id指定なし)
func (cr *MyController) DeleteMany(cx *goweb.
Context) {
fmt.Fprintf(cx.ResponseWriter, "Delete many
resources")
}
- 30. GoWebの簡単な使い方 RESTful API
func main() {
controller := new(MyController)
goweb.MapRest("/api", controller)
goweb.ListenAndServe(":8080")
}
https://github.com/golang-samples/goweb/tree/master/rest
- 33. 話きれなかったこと
● テンプレートエンジン
○ html/template, text/template
● テスト
○ net/http/httptest
● FastCGI
○ net/http/fcgi
○ nginxなどで使用
● gowebの具体的な使用例
○ AngularJSから使う
○ https://github.com/golang-
samples/goweb/tree/master/diary
- 36. Go言語が使えるエディタ/IDE
● https://code.google.com/p/go-
wiki/wiki/IDEsAndTextEditorPlugin
s
● Vim
● Emacs
● Sublime Text
● LiteIDE
● Goclipse(Eclipse)
● Goworks(Netbeans)