2019-07-31 13:47:30 -08:00
|
|
|
package webcontext
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ctxKey represents the type of value for the context key.
|
2019-07-31 18:34:27 -08:00
|
|
|
type ctxKeyValues int
|
2019-07-31 13:47:30 -08:00
|
|
|
|
|
|
|
// KeyValues is how request values or stored/retrieved.
|
2019-07-31 18:34:27 -08:00
|
|
|
const KeyValues ctxKeyValues = 1
|
2019-07-31 13:47:30 -08:00
|
|
|
|
|
|
|
var ErrContextRequired = errors.New("web value missing from context")
|
|
|
|
|
|
|
|
// Values represent state for each request.
|
|
|
|
type Values struct {
|
|
|
|
Now time.Time
|
|
|
|
TraceID uint64
|
|
|
|
SpanID uint64
|
|
|
|
StatusCode int
|
|
|
|
Env Env
|
2019-08-02 15:03:32 -08:00
|
|
|
RequestIP string
|
2019-07-31 13:47:30 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
func ContextValues(ctx context.Context) (*Values, error) {
|
|
|
|
// If the context is missing this value, request the service
|
|
|
|
// to be shutdown gracefully.
|
|
|
|
v, ok := ctx.Value(KeyValues).(*Values)
|
|
|
|
if !ok {
|
|
|
|
e := Values{}
|
|
|
|
return &e, ErrContextRequired
|
|
|
|
}
|
|
|
|
|
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type Env = string
|
|
|
|
|
|
|
|
var (
|
|
|
|
Env_Dev Env = "dev"
|
|
|
|
Env_Stage Env = "stage"
|
|
|
|
Env_Prod Env = "prod"
|
|
|
|
)
|
|
|
|
|
|
|
|
func ContextEnv(ctx context.Context) string {
|
|
|
|
cv := ctx.Value(KeyValues).(*Values)
|
|
|
|
if cv != nil {
|
|
|
|
return cv.Env
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|