best way and race free case to transfer some value in context to caller

49 views
Skip to first unread message

Vasiliy Tolstov

unread,
Feb 11, 2021, 3:48:57 PM2/11/21
to golang-nuts
Hi. i have func like func AAA(ctx context.Context, req interface{}) error {}
inside func i need to return some value not via error, but in context
(as i only one way do do that)
I'm write something like code below. I can't transfer code inside
error, because it predefined struct (generated from protobuf) and i
cant use grpc Outcoming context and grpc as this is not grpc
server/client code.
What the best way? And the next question - does it possible to clone
context with all deadlines and internal stuff without creating some
struct that satisfies context and uses in as parentheses?

```go
type rspCodeKey struct{}
type rspCodeVal struct {
code int
}

func SetRspCode(ctx context.Context, code int) {
if rsp, ok := ctx.Value(rspCodeKey{}).(*rspCodeVal); ok {
rsp.code = code
}
}

func GetRspCode(ctx context.Context) int {
var code int
if rsp, ok := ctx.Value(rspCodeKey{}).(*rspCodeVal); ok {
code = rsp.code
}
return code
}
```

--
Vasiliy Tolstov,
e-mail: v.to...@selfip.ru
Reply all
Reply to author
Forward
0 new messages