Skip to content

建议:session 接口增加 ctx 参数 #21

Description

@xmx

方法调用时传递 ctx 可以由调用者灵活控制。
在一些特殊情况下,例如:
将 session 存在了数据库或 redis 等外部系统中,由于网络波动或性能差,导致 session 操作耗时,
客户端可能超时或主动取消了请求,但是没有 ctx 的控制,session 操作仍然可能还在操作中。
虽然 session 实现者可以指定一个带超时时间的 ctx,但是该 ctx 很难与客户端的请求的 ctx 产生关联(http.Request.Context())。

效果如下:

type Session interface {
	GetSession(ctx context.Context, id string) (value interface{}, err error)
	SetSession(ctx context.Context, id string, value interface{}) error
	DelSession(ctx context.Context, id string) error
}

ship.Context 实现可改为:

func (c *Context) GetSession(ctx context.Context, id string) (v interface{}, err error) {
	if ctx == nil {
		ctx = c.req.Context()
	}
	if id == "" {
		err = ErrInvalidSession
	} else if v, err = c.Session.GetSession(ctx, id); err == nil && v == nil {
		err = ErrSessionNotExist
	}

	return
}

func (c *Context) SetSession(ctx context.Context, id string, value interface{}) (err error) {
	if id == "" || value == nil {
		return ErrInvalidSession
	}
	if ctx == nil {
		ctx = c.req.Context()
	}
	return c.Session.SetSession(ctx, id, value)
}

func (c *Context) DelSession(ctx context.Context, id string) (err error) {
	if id == "" {
		return ErrInvalidSession
	}
	if ctx == nil {
		ctx = c.req.Context()
	}
	return c.Session.DelSession(ctx, id)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions