github.com/storacha/go-ucanto@v0.7.2/transport/headercar/codec.go (about) 1 package headercar 2 3 import ( 4 "net/http" 5 6 "github.com/storacha/go-ucanto/core/message" 7 "github.com/storacha/go-ucanto/transport" 8 hcmsg "github.com/storacha/go-ucanto/transport/headercar/message" 9 "github.com/storacha/go-ucanto/transport/headercar/request" 10 "github.com/storacha/go-ucanto/transport/headercar/response" 11 thttp "github.com/storacha/go-ucanto/transport/http" 12 ) 13 14 type OutboundCodec struct{} 15 16 func (oc *OutboundCodec) Encode(msg message.AgentMessage) (transport.HTTPRequest, error) { 17 return request.Encode(msg) 18 } 19 20 func (oc *OutboundCodec) Decode(res transport.HTTPResponse) (message.AgentMessage, error) { 21 return response.Decode(res) 22 } 23 24 var _ transport.OutboundCodec = (*OutboundCodec)(nil) 25 26 func NewOutboundCodec() *OutboundCodec { 27 return &OutboundCodec{} 28 } 29 30 type InboundAcceptCodec struct{} 31 32 func (cic *InboundAcceptCodec) Encoder() transport.ResponseEncoder { 33 return cic 34 } 35 36 func (cic *InboundAcceptCodec) Decoder() transport.RequestDecoder { 37 return cic 38 } 39 40 func (cic *InboundAcceptCodec) Encode(msg message.AgentMessage) (transport.HTTPResponse, error) { 41 return response.Encode(msg) 42 } 43 44 func (cic *InboundAcceptCodec) Decode(req transport.HTTPRequest) (message.AgentMessage, error) { 45 return request.Decode(req) 46 } 47 48 type InboundCodec struct { 49 codec transport.InboundAcceptCodec 50 } 51 52 func (ic *InboundCodec) Accept(req transport.HTTPRequest) (transport.InboundAcceptCodec, transport.HTTPError) { 53 msgHdr := req.Headers().Get(hcmsg.HeaderName) 54 if msgHdr == "" { 55 return nil, thttp.NewHTTPError( 56 "The server cannot process the request because the payload format is not supported. Please send the X-Agent-Message header.", 57 http.StatusUnsupportedMediaType, 58 http.Header{}, 59 ) 60 } 61 return ic.codec, nil 62 } 63 64 var _ transport.InboundCodec = (*InboundCodec)(nil) 65 66 func NewInboundCodec() transport.InboundCodec { 67 return &InboundCodec{codec: &InboundAcceptCodec{}} 68 }