2020-03-20 23:22:32 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
|
|
|
|
package ghttp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"github.com/gogf/gf/container/gvar"
|
|
|
|
)
|
|
|
|
|
2020-04-06 22:31:45 +08:00
|
|
|
// Context is alias for function GetCtx.
|
2020-03-21 13:32:43 +08:00
|
|
|
// This function overwrites the http.Request.Context function.
|
2020-04-06 22:31:45 +08:00
|
|
|
// See GetCtx.
|
2020-03-20 23:22:32 +08:00
|
|
|
func (r *Request) Context() context.Context {
|
|
|
|
if r.context == nil {
|
|
|
|
r.context = r.Request.Context()
|
|
|
|
}
|
|
|
|
return r.context
|
|
|
|
}
|
|
|
|
|
2020-04-06 22:31:45 +08:00
|
|
|
// GetCtx retrieves and returns the request's context.
|
2020-03-20 23:22:32 +08:00
|
|
|
func (r *Request) GetCtx() context.Context {
|
|
|
|
return r.Context()
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetCtxVar retrieves and returns a Var with given key name.
|
2020-04-06 22:31:45 +08:00
|
|
|
// The optional parameter <def> specifies the default value of the Var if given <key>
|
|
|
|
// does not exist in the context.
|
2020-03-20 23:22:32 +08:00
|
|
|
func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var {
|
|
|
|
value := r.Context().Value(key)
|
|
|
|
if value == nil && len(def) > 0 {
|
|
|
|
value = def[0]
|
|
|
|
}
|
|
|
|
return gvar.New(value)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetCtxVar sets custom parameter to context with key-value pair.
|
|
|
|
func (r *Request) SetCtxVar(key interface{}, value interface{}) {
|
|
|
|
r.context = context.WithValue(r.Context(), key, value)
|
|
|
|
}
|