go.uber.org/yarpc@v1.72.1/encoding/raw/inbound.go (about) 1 // Copyright (c) 2022 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package raw 22 23 import ( 24 "context" 25 "io/ioutil" 26 27 encodingapi "go.uber.org/yarpc/api/encoding" 28 "go.uber.org/yarpc/api/transport" 29 "go.uber.org/yarpc/pkg/errors" 30 ) 31 32 // rawUnaryHandler adapts a Handler into a transport.UnaryHandler 33 type rawUnaryHandler struct{ UnaryHandler } 34 35 // rawOnewayHandler adapts a Handler into a transport.OnewayHandler 36 type rawOnewayHandler struct{ OnewayHandler } 37 38 func (r rawUnaryHandler) Handle(ctx context.Context, treq *transport.Request, rw transport.ResponseWriter) error { 39 if err := errors.ExpectEncodings(treq, Encoding); err != nil { 40 return err 41 } 42 43 ctx, call := encodingapi.NewInboundCall(ctx) 44 if err := call.ReadFromRequest(treq); err != nil { 45 return err 46 } 47 48 reqBody, err := ioutil.ReadAll(treq.Body) 49 if err != nil { 50 return err 51 } 52 53 resBody, appErr := r.UnaryHandler(ctx, reqBody) 54 if err := call.WriteToResponse(rw); err != nil { 55 return err 56 } 57 58 // we want to return the appErr if it exists as this is what 59 // the previous behavior was so we deprioritize this error 60 var writeErr error 61 if len(resBody) > 0 { 62 _, writeErr = rw.Write(resBody) 63 } 64 if appErr != nil { 65 rw.SetApplicationError() 66 return appErr 67 } 68 return writeErr 69 } 70 71 func (r rawOnewayHandler) HandleOneway(ctx context.Context, treq *transport.Request) error { 72 if err := errors.ExpectEncodings(treq, Encoding); err != nil { 73 return err 74 } 75 76 ctx, call := encodingapi.NewInboundCall(ctx) 77 if err := call.ReadFromRequest(treq); err != nil { 78 return err 79 } 80 81 reqBody, err := ioutil.ReadAll(treq.Body) 82 if err != nil { 83 return err 84 } 85 86 return r.OnewayHandler(ctx, reqBody) 87 }