Hello,

> Could the context replace the custom session data structures ?

You mean `filter.SessionData`? Indeed, but I recommend to use a concrete type to make the API more clear and to avoid all those nasty type assertions (slightly off-topic, in newer versions of Go, empty interfaces should be `any`, not `interface{}`).

For instance, if you want to pass some sender data, you can use the following idiom:

// Not exported custom type to avoid context map key collision.
type key int
var sessionSenderKey key = 1

// Type available in the context.
type SessionSender struct {
    Name string
    Address string
}

// Set the value.
func NewSessionSenderContext(ctx context.Context,
    s SessionSender) context.Context {
    return context.WithValue(ctx, sessionSenderKey, s)
}

// Consumers retrieve the value with this.
func FromSessionSenderContext(ctx context.Context)
    (SessionSender, bool) {
    s, ok := ctx.Value(sessionSenderKey).(SessionSender)
    if !ok {
        return SessionSender{}, ok
    }

    return s, ok
}

// This is not necessary, but if the value is always expected, it makes // retrieving it a lot easier because you avoid the whole "if value, ok" // idiom.
func MustFromSessionSenderContext(ctx context.Context) SessionSender {
    s, ok := FromSessionSenderContext(ctx)
    if !ok {
        panic(`key does not exist`)
    }

    return s
}

With the above pattern you can invent any other necessary data structure that should pass between service calls.

Here's how to set and pass it:

s := SessionSender{Name: `Foo`, Address: `f...@bar.org`}
ctx := context.Background()
ctx = NewSessionSenderContext(ctx, s)

// Noticed I removed `Session` from function signature to make it more // simple? Instead you can include that in another context or just pass // it as a regular string if the session ID is essential in every call.
dir.linkGreeting(ctx, timestamp, atoms[0])

Now the consumers can get the value if they are interested in it.

func linkGreetingCb(ctx context.Context, timestamp time.Time,
    hostname string) {
    fmt.Fprintf(os.Stderr, "%s: %v: link-greeting: %s\n", timestamp,
        filter.MustFromSessionSenderContext(ctx), hostname)
}

And that's how passing values between calls goes.

With regard,

On 6/12/24 12:37, gil...@poolp.org wrote:
> June 12, 2024 11:05 AM, "Igor Zornik" <moche...@mocheryl.org> wrote:
>
>> Hello,
>>
>> Would it make sense to include context as the first parameter in each API call? That's how Go >> usually handles service calls. Then you may use it to pass any arbitrary values or perform
>> operation cancellations.
>>
>> With regards
>>
>
> That's an interesting question.
>
> Could the context replace the custom session data structures ?
>
> I need to look into it, thanks for pointing it.

Reply via email to