Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Convert RPC style function into http.Handler

License

NotificationsYou must be signed in to change notification settings

acoshift/hrpc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build StatuscodecovGo Report CardGoDoc

Convert RPC style function into http.Handler

Support input types

  • context.Context
  • *http.Request
  • http.ResponseWriter
  • any

Support output types

  • any
  • error

Usage

import"github.com/acoshift/hrpc/v3"

Create new hrpc Manager

m:= hrpc.Manager{Decoder:func(r*http.Request,dstany)error {returnjson.NewDecoder(r.Body).Decode(dst)},Encoder:func(w http.ResponseWriter,r*http.Request,resany) {w.Header().Set("Content-Type","application/json; charset=utf-8")json.NewEncoder(w).Encode(res)},ErrorEncoder:func(w http.ResponseWriter,r*http.Request,errerror) {res:=&struct {Errorstring`json:"error"`}{err.Error()}w.Header().Set("Content-Type","application/json; charset=utf-8")w.WriteHeader(http.StatusInternalServerError)json.NewEncoder(w).Encode(res)},Validate:true,}

RPC style function

typeUserRequeststruct {IDint`json:"id"`}func (req*UserRequest)Valid()error {// Valid will be called when decode, if set validate to trueifreq.ID<=0 {returnfmt.Errorf("invalid id")}returnnil}typeUserResponsestruct {IDint`json:"id"`Usernamestring`json:"username"`}http.Handle("/user.get",m.Handler(func(ctx context.Context,req*UserRequest) (*UserResponse,error) {return&UserResponse{ID:1,Username:"acoshift"},nil}))// or use non-ptr structhttp.Handle("/user.get2",m.Handler(func(ctx context.Context,reqUserRequest) (resUserResponse,errerror) {res.ID=1res.Username="acoshift"return}))

gRPC service client (generated from .proto)

m.Handler(func(ctx context.Context,in*UserRequest,opts...grpc.CallOption) (*UserResponse,error) {returnnil,errors.New("not implemented")})

Mixed types

m.Handler(func(r*http.Request)error {buf:=&bytes.Buffer{}_,err:=io.Copy(buf,r.Body)iferr!=nil {returnerr}fmt.Printf("upload data: %s\n",buf.String())returnnil})m.Handler(func(w http.ResponseWriter,r*http.Request) {})m.Handler(func(ctx context.Context,r*http.Request,w http.ResponseWriter) {})

About

Convert RPC style function into http.Handler

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp