gorillaでAPIサーバを書く 1
gorillaを使ってAPIサーバを書く。
ディレクトリ構成としては、以下を想定。
.api │ ├── handlers │ ├── core.go │ └── router.go └── api.go
それぞれのファイルは大まかに以下のような役割になります。
- api.goはサーバの起動設定などを記載
- router.goはファイル名の通りrouterなので、パスに合わせたハンドラの設定
- core.goはハンドラーの実装
まずは必要なパッケージのインストール
go get github.com/gorilla/mux
api.goはgorilla特有の処理などは書かないので割愛。
router.go では、mux.Routerを使ったRouter関数を定義します。 エンドポイントを指定して、エンドポイントごとにHTTPメソッドに対応するHandler関数を設定します。
package handlers import ( "net/http" "github.com/gorilla/mux" ) const ( RegexMatchUserID = "[A-Za-z0-9]{3}" ) func Router() *mux.Router { r := mux.NewRouter() s := r.PathPrefix("/api/"). Subrouter().StrictSlash(false) usersPath := "/users/" subpath := usersPath + "{userId:" + RegexMatchUserID + "}" s.HandleFunc(usersPath, GetUsers).Methods("GET") s.HandleFunc(subpath, GetUserById).Methods("GET") s.HandleFunc(subpath, DeleteUserById).Methods("DELETE") s.HandleFunc(subpath, CreateUser).Methods("POST"). Headers("Content-Type", "application/json") return r }
PathPrefixでベースとなるURLを元にエンドポイントを組み立て行く方法の他に、下記のようにPathとPathPrefixを組み合わて同じように書くことが出来ます。
func Router() *mux.Router { r := mux.NewRouter() userPath := urlbase + "/users/" users := r.Path(userPath).Subrouter() users.Methods("GET").HandlerFunc(GetUsers) subpath := userPath + "{userId:" + RegexMatchUserID + "}" usr := r.PathPrefix(subpath).Subrouter() usr.Methods("GET").HandlerFunc(GetUserById) usr.Methods("DELETE").HandlerFunc(DeleteUserById) usr.Methods("POST").HandlerFunc(CreateUser) return r }
Handlerメソッドについては、次回記載します。