httprpc

package
v0.0.0-...-9c8aaae Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2021 License: MIT Imports: 19 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var ClientTemplate = template.Must(template.New("").Funcs(map[string]interface{}{
	"ToLowerCamel": strcase.ToLowerCamel,
	"ToUpperCamel": strcase.ToUpperCamel,
	"ToURLPath":    httprpc.URLPath,
}).Parse(strings.TrimSpace(`
// Code generated by go-codegen api protobuf go_client httprpc; DO NOT EDIT

package {{.PackageName}}

{{.ImportPackages}}

{{$rootParam := .}}

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 NewJSONBodyMarshaler() BodyMarshaler {
	return NewBodyMarshaler(
		func(v proto.Message) ([]byte, error) {
			return json.Marshal(v)
		},
		"application/json",
	)
}

func NewProtoBodyMarshaler() BodyMarshaler {
	return NewBodyMarshaler(
		proto.Marshal,
		"application/protobuf",
	)
}

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 NewJSONBodyUnmarshaler() BodyUnmarshaler {
	return NewBodyUnmarshaler(
		func(data []byte, v proto.Message) error {
			return json.Unmarshal(data, v)
		},
	)
}

func NewProtoBodyUnmarshaler() BodyUnmarshaler {
	return NewBodyUnmarshaler(
		proto.Unmarshal,
	)
}

func NewClient(
	httpClient *http.Client,
	urlBase url.URL,
	bodyMarshaler BodyMarshaler,
	bodyUnmarshaler BodyUnmarshaler,
	handleErrorResponse func(resp *http.Response) error,
) Client {
	return Client{
		httpClient: httpClient,
		urlBase: urlBase,
		bodyMarshaler: bodyMarshaler,
		bodyUnmarshaler: bodyUnmarshaler,
		handleErrorResponse: handleErrorResponse,
	}
}

type Client struct {
	httpClient *http.Client
	urlBase url.URL
	bodyMarshaler BodyMarshaler
	bodyUnmarshaler BodyUnmarshaler
	handleErrorResponse func(resp *http.Response) error
}

{{- range .Services}}
{{$service := .}}
{{- range .RPCs}}

{{$returnError := "return err"}}
{{if .OutputClientType}}
{{$returnError = "return output, err"}}
{{end}}

func (c Client){{.Name}}(ctx context.Context, input {{.InputClientType.Obj.Name}}) ({{if .OutputClientType}}output {{.OutputClientType.Obj.Name}}, err {{end}}error) {
	u := c.urlBase
	u.Path = path.Join(u.Path, "{{ToURLPath $service.Obj.Name .Name}}")

	inputProtoType := {{$rootParam.TypePrinter.PrintConverterWitoutErrorCheck "input" .InputClientType .InputProtoType}}
	b, err := c.bodyMarshaler.Marshal(&inputProtoType)
	if err != nil {
		{{$returnError}}
	}
	r, err := http.NewRequest("POST", u.String(), bytes.NewReader(b))
	if err != nil {
		{{$returnError}}
	}
	r = r.WithContext(ctx)
	r.Header.Set("Content-Type", c.bodyMarshaler.ContentType())

	resp, err := c.httpClient.Do(r)
	if err != nil {
		{{$returnError}}
	}
	defer func() {
		io.Copy(ioutil.Discard, resp.Body)
		resp.Body.Close()
	}()

	if resp.StatusCode >= 400 {
		err := c.handleErrorResponse(resp)
		{{$returnError}}
	}

	{{- if .OutputClientType}}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		err = zaperr.Wrap(err, "failed to read response body", zap.Int("statusCode", resp.StatusCode))
		{{$returnError}}
	}
	outputProtoType := {{$rootParam.TypePrinter.PrintRelativeType .OutputProtoType}}{}
	if err := c.bodyUnmarshaler.Unmarshal(body, &outputProtoType); err != nil {
		err = zaperr.Wrap(err, "failed to parse response body", zap.String("body", string(body)))
		{{$returnError}}
	}
	return {{$rootParam.TypePrinter.PrintConverterWitoutErrorCheck "outputProtoType" .OutputProtoType .OutputClientType}}, nil
	{{- else}}
	return nil
	{{- end}}
}
{{- end}}
{{- end}}
`)))
View Source
var ClientTemplateUsedPackages = []*types.Package{
	types.NewPackage("net/http", "http"),
	types.NewPackage("net/url", "url"),
	types.NewPackage("bytes", "bytes"),
	types.NewPackage("context", "context"),
	types.NewPackage("io", "io"),
	types.NewPackage("io/ioutil", "ioutil"),
	types.NewPackage("path", "path"),
	types.NewPackage("go.uber.org/zap", "zap"),
	types.NewPackage("github.com/hori-ryota/zaperr", "zaperr"),
	types.NewPackage("encoding/json", "json"),
	types.NewPackage("google.golang.org/protobuf/proto", "proto"),
}

Functions

func Generate

func Generate(
	usecasePkgInfo *loader.PackageInfo,
	protoPkgInfo *loader.PackageInfo,
	clientTypedefPkgInfo *loader.PackageInfo,
	dstPackage *types.Package,
) (string, error)

func NewHttprpcCmd

func NewHttprpcCmd() *cobra.Command

func Run

func Run(
	usecaseDir string,
	protoDir string,
	clientTypedefDir string,
	outputDir string,
	useStdOut bool,
) error

Types

type RPC

type RPC struct {
	*types.Func
	InputProtoType   *types.Named
	InputClientType  *types.Named
	OutputProtoType  *types.Named
	OutputClientType *types.Named
}

func ParseRPC

func ParseRPC(method *types.Func, protoPkgInfo *loader.PackageInfo, clientTypedefPkgInfo *loader.PackageInfo) (*RPC, error)

type Service

type Service struct {
	*types.Named
	RPCs []RPC
}

type TemplateParam

type TemplateParam struct {
	PackageName    string
	ImportPackages string
	Services       []Service
	TypePrinter    typeutil.Printer
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL