github.com/storacha/go-ucanto@v0.7.2/transport/car/response/response.go (about) 1 package response 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/storacha/go-ucanto/core/car" 8 "github.com/storacha/go-ucanto/core/dag/blockstore" 9 "github.com/storacha/go-ucanto/core/ipld" 10 "github.com/storacha/go-ucanto/core/message" 11 "github.com/storacha/go-ucanto/transport" 12 uhttp "github.com/storacha/go-ucanto/transport/http" 13 ) 14 15 const ContentType = car.ContentType 16 17 func Encode(msg message.AgentMessage) (transport.HTTPResponse, error) { 18 headers := http.Header{} 19 headers.Add("Content-Type", car.ContentType) 20 reader := car.Encode([]ipld.Link{msg.Root().Link()}, msg.Blocks()) 21 return uhttp.NewResponse(http.StatusOK, reader, headers), nil 22 } 23 24 func Decode(response transport.HTTPResponse) (message.AgentMessage, error) { 25 roots, blocks, err := car.Decode(response.Body()) 26 if err != nil { 27 return nil, fmt.Errorf("decoding CAR: %w", err) 28 } 29 if len(roots) != 1 { 30 return nil, fmt.Errorf("unexpected number of roots: %d, expected: 1", len(roots)) 31 } 32 bstore, err := blockstore.NewBlockReader(blockstore.WithBlocksIterator(blocks)) 33 if err != nil { 34 return nil, fmt.Errorf("creating blockstore: %w", err) 35 } 36 return message.NewMessage(roots[0], bstore) 37 }