grpc-gatewayにAPIを実装する

これはかなりおすすめしないですが、とりあえず検証ということでやってみました。

helthcheckぐらいならいいかも?

まずは、登録するハンドラーを用意。

package echo

import (
    "io"
    "net/http"

    "github.com/grpc-ecosystem/grpc-gateway/runtime"
    "google.golang.org/grpc/grpclog"
)

func RegisterEchoHandlerFromEndpoint(mux *runtime.ServeMux) (err error) {
    // endpoint: /echo
    mux.Handle("GET", pattern_echo, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
        // レスポンスを書き込む
        if _, err = w.Write([]byte("hello.")); err != nil {
            grpclog.Printf("Failed to write response: %v", err)
        }
    })

    return nil
}

var (
    pattern_echo = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"echo"}, ""))
)

あとは登録するだけで動きます。

   ...
 
    if err := gw_echo.RegisterEchoHandlerFromEndpoint(mux); err != nil {
        return err
    }

    return http.ListenAndServe(":8080", mux)

リクエストしてみる。

→ curl -i -XGET http://localhost:8080/echo
HTTP/1.1 200 OK
Date: Thu, 18 Jan 2018 09:40:38 GMT
Content-Length: 6
Content-Type: text/plain; charset=utf-8

hello.%