protoc-gen-go-micro/templates/micro_chi.pb.go.tmpl
Vasiliy Tolstov bd881473cb add ability to generate gorilla and chi helpers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-19 12:43:37 +03:00

51 lines
1.5 KiB
Cheetah

// Code generated by protoc-gen-micro
package {{goPkgLastElement .File | splitArray ";" | last}}
import (
"context"
"fmt"
"net/http"
"reflect"
"strings"
"github.com/go-chi/chi/v4"
middleware "github.com/go-chi/chi/v4/middleware"
micro_api "github.com/unistack-org/micro/v3/api"
)
type routeKey struct{}
func RouteName(ctx context.Context) (string, bool) {
value, ok := ctx.Value(routeKey{}).(string)
return value, ok
}
func Register(r *chi.Mux, h interface{}, eps []*micro_api.Endpoint) error {
v := reflect.ValueOf(h)
if v.NumMethod() < 1 {
return fmt.Errorf("invalid handler specified: %#+v", h)
}
for _, ep := range eps {
idx := strings.Index(ep.Name, ".")
if idx < 1 || len(ep.Name) <= idx {
return fmt.Errorf("invalid api.Endpoint name: %s", ep.Name)
}
name := ep.Name[idx+1:]
m := v.MethodByName(name)
if !m.IsValid() || m.IsZero() {
return fmt.Errorf("invalid handler, method %s not found", name)
}
rh, ok := m.Interface().(func(http.ResponseWriter, *http.Request))
if !ok {
return fmt.Errorf("invalid handler: %#+v", m.Interface())
}
for _, method := range ep.Method {
r.With(middleware.Value(routeKey{}, ep.Name)).MethodFunc(method, ep.Path[0], rh)
}
}
return nil
}