Documentation ¶
Overview ¶
Copyright © 2019 hori-ryota <hori.ryota@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Index ¶
- Variables
- func Generate(usecasePkgInfo *loader.PackageInfo, protoPkgInfo *loader.PackageInfo, ...) (string, error)
- func NewHttprpcCmd() *cobra.Command
- func Run(usecaseDir string, protoDir string, outputDir string, useStdOut bool) error
- func URLPath(serviceName string, rpcName string) string
- type RPC
- type Service
- type TemplateParam
Constants ¶
This section is empty.
Variables ¶
var HandlerTemplate = template.Must(template.New("").Funcs(map[string]interface{}{ "ToLowerCamel": strcase.ToLowerCamel, "ToUpperCamel": strcase.ToUpperCamel, "ToURLPath": URLPath, "ExtractActorDescriptorOrNil": extractActorDescriptorOrNil, "ExtractActorDescriptors": func(rootParam TemplateParam) []*types.Var { actors := make(map[string]*types.Var, 10) for _, s := range rootParam.Services { for _, rpc := range s.RPCs { actor := extractActorDescriptorOrNil(rpc) if actor == nil { continue } n := actor.Name() + "_" + actor.Type().String() actors[n] = actor } } names := make([]string, 0, len(actors)) for k := range actors { names = append(names, k) } sort.Strings(names) results := make([]*types.Var, 0, len(names)) for _, k := range names { results = append(results, actors[k]) } return results }, "ToActorParserTypeName": toActorParserTypeName, "ToActorParseMethodName": toActorParseMethodName, }).Parse(strings.TrimSpace(` // Code generated by go-codegen api protobuf go_server httprpc; DO NOT EDIT package {{.PackageName}} {{.ImportPackages}} {{$rootParam := .}} {{$actors := ExtractActorDescriptors $rootParam}} type ErrorType string const ( FailedToReadRequestError ErrorType = "failed to read request" FailedToUnmarshalRequestError ErrorType = "failed to unmarshal request" FailedToGenerateUsecaseError ErrorType = "failed to generate usecase" FailedToParseActorDescriptorError ErrorType = "failed to parse actor descriptor" FromUsecaseError ErrorType = "from usecase error" FailedToMarshalResponseError ErrorType = "failed to marshal response" FailedToWriteResponseError ErrorType = "failed to write response" ) type BodyMarshaler interface { Marshal(v proto.Message) (data []byte, err error) ContentType() string } type bodyMarshaler struct { marshalFunc func(v proto.Message) (data []byte, err error) contentType string } func (m bodyMarshaler) Marshal(v proto.Message) ([]byte, error) { return m.marshalFunc(v) } func (m bodyMarshaler) ContentType() string { return m.contentType } func NewBodyMarshaler( marshalFunc func(v proto.Message) (data []byte, err error), contentType string, ) BodyMarshaler { return bodyMarshaler{ marshalFunc: marshalFunc, contentType: contentType, } } func NewProtoBodyMarshaler() BodyMarshaler { return NewBodyMarshaler( proto.Marshal, "application/protobuf", ) } func NewJSONBodyMarshaler() BodyMarshaler { return NewBodyMarshaler( func(v proto.Message) ([]byte, error) { return json.Marshal(v) }, "application/json", ) } func NewProtoJSONBodyMarshaler() BodyMarshaler { return NewBodyMarshaler( func(v proto.Message) ([]byte, error) { return protojson.Marshal(v) }, "application/json", ) } type BodyUnmarshaler interface { Unmarshal(data []byte, v proto.Message) error } type bodyUnmarshaler struct { unmarshalFunc func(data []byte, v proto.Message) error } func (m bodyUnmarshaler) Unmarshal(data []byte, v proto.Message) error { return m.unmarshalFunc(data, v) } func NewBodyUnmarshaler( unmarshalFunc func(data []byte, v proto.Message) error, ) BodyUnmarshaler { return bodyUnmarshaler{ unmarshalFunc: unmarshalFunc, } } func NewProtoBodyUnmarshaler() BodyUnmarshaler { return NewBodyUnmarshaler( proto.Unmarshal, ) } func NewProtoJSONBodyUnmarshaler() BodyUnmarshaler { return NewBodyUnmarshaler( func(data []byte, v proto.Message) error { return protojson.Unmarshal(data, v) }, ) } func NewHandlers( handleError func(w http.ResponseWriter, r *http.Request, errorType ErrorType, err error), bodyMarshaler BodyMarshaler, bodyUnmarshaler BodyUnmarshaler, {{- range .Services}} {{ToLowerCamel .Obj.Name}}Factory {{ToUpperCamel .Obj.Name}}Factory, {{- end}} {{- range $actors}} {{ToLowerCamel (ToActorParserTypeName $rootParam.TypePrinter .)}} {{ToActorParserTypeName $rootParam.TypePrinter .}}, {{- end}} ) Handlers { return Handlers{ HandleError: handleError, bodyMarshaler: bodyMarshaler, bodyUnmarshaler: bodyUnmarshaler, {{- range .Services}} {{ToUpperCamel .Obj.Name}}Factory: {{ToLowerCamel .Obj.Name}}Factory, {{- end}} {{- range $actors}} {{ToUpperCamel (ToActorParserTypeName $rootParam.TypePrinter .)}}: {{ToLowerCamel (ToActorParserTypeName $rootParam.TypePrinter .)}}, {{- end}} } } type Handlers struct { HandleError func(w http.ResponseWriter, r *http.Request, errorType ErrorType, err error) bodyMarshaler BodyMarshaler bodyUnmarshaler BodyUnmarshaler {{- range .Services}} {{ToUpperCamel .Obj.Name}}Factory {{ToUpperCamel .Obj.Name}}Factory {{- end}} {{- range $actors }} {{ToUpperCamel (ToActorParserTypeName $rootParam.TypePrinter .)}} {{ToActorParserTypeName $rootParam.TypePrinter .}} {{- end}} } {{- range $actors }} type {{ToActorParserTypeName $rootParam.TypePrinter .}} interface { {{ToActorParseMethodName $rootParam.TypePrinter .}}(context.Context, *http.Request) ({{$rootParam.TypePrinter.PrintRelativeType .Type}}, error) } {{- end}} {{- range .Services}} type {{.Obj.Name}}Factory interface { Generate{{.Obj.Name}}(context.Context) ({{$rootParam.TypePrinter.PrintRelativeType .Named}}, error) } type Static{{.Obj.Name}}Factory struct { usecase {{$rootParam.TypePrinter.PrintRelativeType .Named}} } func NewStatic{{.Obj.Name}}Factory(usecase {{$rootParam.TypePrinter.PrintRelativeType .Named}}) Static{{.Obj.Name}}Factory { return Static{{.Obj.Name}}Factory{usecase:usecase} } func (f Static{{.Obj.Name}}Factory) Generate{{.Obj.Name}}(ctx context.Context) ({{$rootParam.TypePrinter.PrintRelativeType .Named}}, error) { return f.usecase, nil } {{$service := .}} {{- range .RPCs}} func (h Handlers){{ToUpperCamel $service.Obj.Name}}{{.Name}}Handler(w http.ResponseWriter, r *http.Request) { if h.{{$service.Obj.Name}}Factory == nil { w.WriteHeader(http.StatusNotImplemented) return } body, err := ioutil.ReadAll(r.Body) if err != nil { h.HandleError(w, r, FailedToReadRequestError, err) return } inputProtoType := {{$rootParam.TypePrinter.PrintRelativeType .InputProtoType}}{} if err := h.bodyUnmarshaler.Unmarshal(body, &inputProtoType); err != nil { h.HandleError(w, r, FailedToUnmarshalRequestError, err) return } input := {{$rootParam.TypePrinter.PrintConverterWitoutErrorCheck "inputProtoType" .InputProtoType .InputType}} usecase, err := h.{{$service.Obj.Name}}Factory.Generate{{$service.Obj.Name}}(r.Context()) if err != nil { h.HandleError(w, r, FailedToGenerateUsecaseError, err) return } {{- $actor := (ExtractActorDescriptorOrNil .)}} {{- if $actor}} actor, err := h.{{ToUpperCamel (ToActorParserTypeName $rootParam.TypePrinter $actor)}}.{{ToActorParseMethodName $rootParam.TypePrinter $actor}}(r.Context(), r) if err != nil { h.HandleError(w, r, FailedToParseActorDescriptorError, err) return } {{- end}} {{- if .OutputType}} outputType, err := usecase.{{.Name}}( r.Context(), input,{{if $actor}} actor,{{end}} ) if err != nil { h.HandleError(w, r, FromUsecaseError, err) return } outputProtoType := {{$rootParam.TypePrinter.PrintConverterWitoutErrorCheck "outputType" .OutputType .OutputProtoType}} b, err := h.bodyMarshaler.Marshal(&outputProtoType) if err != nil { h.HandleError(w, r, FailedToMarshalResponseError, err) return } w.Header().Set("Content-Type", h.bodyMarshaler.ContentType()) if _, err := w.Write(b); err != nil { h.HandleError(w, r, FailedToWriteResponseError, err) return } return {{- else}} if err := usecase.{{.Name}}( r.Context(), input,{{if $actor}} actor,{{end}} ); err != nil { h.HandleError(w, r, FromUsecaseError, err) return } return {{- end}} } {{- end}} {{- end}} func NewMux(handler Handlers, middlewares ...func(http.Handler) http.Handler) *http.ServeMux { mux := http.NewServeMux() ApplyMux(mux, handler, middlewares...) return mux } func ApplyMux(mux *http.ServeMux, handler Handlers, middlewares ...func(http.Handler) http.Handler) { {{- range .Services}} {{$service := .}} {{- range .RPCs}} mux.Handle( "/{{ToURLPath $service.Obj.Name .Name}}", applyMiddleware(http.HandlerFunc(handler.{{ToUpperCamel $service.Obj.Name}}{{.Name}}Handler), middlewares...), ) {{- end}} {{- end}} } func applyMiddleware(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler { for i := range middlewares { h = middlewares[len(middlewares)-i-1](h) } return h } `)))
var HandlerTemplateUsedPackages = []*types.Package{ types.NewPackage("io/ioutil", "ioutil"), types.NewPackage("net/http", "http"), types.NewPackage("encoding/json", "json"), types.NewPackage("google.golang.org/protobuf/proto", "proto"), types.NewPackage("google.golang.org/protobuf/encoding/protojson", "protojson"), }
Functions ¶
func Generate ¶
func Generate( usecasePkgInfo *loader.PackageInfo, protoPkgInfo *loader.PackageInfo, dstPackage *types.Package, ) (string, error)