LoginSignup
169

More than 5 years have passed since last update.

Go言語でServer作る時に必要な知識メモ

Last updated at Posted at 2015-04-23

基本的に必要な物は、net/httpパッケージに入っている。

import "net/http"

するだけで、基本的なHTTPのリクエストとリスポンスに関する処理を行うことが出来る

http.Handle("/foo", fooHandler)

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

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

ここで、http.Handle, http.HandleFuncすると、DefaultServerMuxと言うものにマッピングが登録される。

ServeMux

  • ServeMux = HTTP request multiplexer
    • リクエストを登録済みのURLパターンリストと照合して、マッチしたHandlerを呼び出す
    • 複数マッチする場合はマッチが長いほうが優先される
    • e.g "/images/thumbnails/", "/images/", "/" という順
    • 逆に言えば、"/"は全てのリクエストにマッチする。そのため本当に"/"だけかはHandler側でチェックする必要がある。
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
   // The "/" pattern matches everything, so we need to check
   // that we're at the root here.
   if req.URL.Path != "/" {
       http.NotFound(w, req)
       return
   }
   fmt.Fprintf(w, "Welcome to the home page!")
})

gorilla/mux

デフォルトのServerMux(Router)は非力なので、gorilla/muxというライブラリが人気を集めている

r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
vars := mux.Vars(request)
category := vars["category"]

というように便利なRoutingができるもの。

Middleware

If your application--your routing, your controllers, your business logic--is the green circle in the center, you can see that the user's request passes through several middleware layers, hits your app, and then passes out through more middleware layers. Any given middleware can operate before the application logic, after it, or both.

onion.png

アプリケーションロジック(自分で書くRouterやControllerが行う部分)を実行する前後に何かしてくれるもの。この図で言えば、緑がアプリケーションロジックで、その周りにいるのがミドルウェア。

negroni

このミドルウェアを導入するのに、今人気を集めてきているライブラリがnegroniこれは、matiniという人気を集めたWeb Frameworkの作者が、Go的じゃないという批判をうけて、それならということで書き直したもの。

これと、gorilla/mux を組み合わせてウェブアプリを作るような web書籍 もあり、参考になる。

WebFramework

まずは、Goなら、Frameworkを使わずにnet/httpだけでやってみるという手も全然ありなことを忘れずに。

Revel

http://revel.github.io/
Go言語の中では一番がっしりしたフレームワーク。Rails的

Martini

http://martini.codegangsta.io/
Revelより軽量なSinatra的フレームワーク。

Negroni

Martiniの作者が、Go的なMiddlewareのみのフレームワークにしたもの。
ルーティングはgorilla/muxと組み合わせろと書いてあったり、ミドルウェアの部分のみをミニマムに実装したもの。

Gin

http://gin-gonic.github.io/gin/
Matiniと同じような軽量フレームワーク。ただMatiniより20倍から45倍速いと書いてある。

Goji

Go-Json-Rest

RestfullなJSON APIを提供しやすい。authやJSONP、gzipなどにも対応できる。
充実したexampleがある https://github.com/ant0ine/go-json-rest-examples

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
169