本文整理汇总了Golang中github.com/gorilla/context.GetOk函数的典型用法代码示例。如果您正苦于以下问题:Golang GetOk函数的具体用法?Golang GetOk怎么用?Golang GetOk使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GetOk函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: TestContextBindAndValidate
func TestContextBindAndValidate(t *testing.T) {
spec, api := petstore.NewAPI(t)
ctx := NewContext(spec, api, nil)
ctx.router = DefaultRouter(spec, ctx.api)
request, _ := http.NewRequest("POST", "/pets", nil)
request.Header.Add("Accept", "*/*")
request.Header.Add("content-type", "text/html")
v, ok := context.GetOk(request, ctxBoundParams)
assert.False(t, ok)
assert.Nil(t, v)
ri, _ := ctx.RouteInfo(request)
data, result := ctx.BindAndValidate(request, ri) // this requires a much more thorough test
assert.NotNil(t, data)
assert.NotNil(t, result)
v, ok = context.GetOk(request, ctxBoundParams)
assert.True(t, ok)
assert.NotNil(t, v)
dd, rr := ctx.BindAndValidate(request, ri)
assert.Equal(t, data, dd)
assert.Equal(t, result, rr)
}
开发者ID:MStoykov,项目名称:go-swagger,代码行数:26,代码来源:context_test.go
示例2: TestContextInvalidResponseFormat
func TestContextInvalidResponseFormat(t *testing.T) {
ct := "application/x-yaml"
other := "application/sgml"
spec, api := petstore.NewAPI(t)
ctx := NewContext(spec, api, nil)
ctx.router = DefaultRouter(spec, ctx.api)
request, _ := http.NewRequest("GET", "http://localhost:8080", nil)
request.Header.Set(httpkit.HeaderAccept, ct)
// check there's nothing there
cached, ok := context.GetOk(request, ctxResponseFormat)
assert.False(t, ok)
assert.Empty(t, cached)
// trigger the parse
mt := ctx.ResponseFormat(request, []string{other})
assert.Empty(t, mt)
// check it was cached
cached, ok = context.GetOk(request, ctxResponseFormat)
assert.False(t, ok)
assert.Empty(t, cached)
// check if the cast works and fetch from cache too
mt = ctx.ResponseFormat(request, []string{other})
assert.Empty(t, mt)
}
开发者ID:MStoykov,项目名称:go-swagger,代码行数:28,代码来源:context_test.go
示例3: TestContextValidContentType
func TestContextValidContentType(t *testing.T) {
ct := "application/json"
ctx := NewContext(nil, nil, nil)
request, _ := http.NewRequest("GET", "http://localhost:8080", nil)
request.Header.Set(httpkit.HeaderContentType, ct)
// check there's nothing there
_, ok := context.GetOk(request, ctxContentType)
assert.False(t, ok)
// trigger the parse
mt, _, err := ctx.ContentType(request)
assert.NoError(t, err)
assert.Equal(t, ct, mt)
// check it was cached
_, ok = context.GetOk(request, ctxContentType)
assert.True(t, ok)
// check if the cast works and fetch from cache too
mt, _, err = ctx.ContentType(request)
assert.NoError(t, err)
assert.Equal(t, ct, mt)
}
开发者ID:MStoykov,项目名称:go-swagger,代码行数:25,代码来源:context_test.go
示例4: TestKeepContext
// Tests that the context is cleared or not cleared properly depending on
// the configuration of the router
func TestKeepContext(t *testing.T) {
func1 := func(w http.ResponseWriter, r *http.Request) {}
r := NewRouter()
r.HandleFunc("/", func1).Name("func1")
req, _ := http.NewRequest("GET", "http://localhost/", nil)
context.Set(req, "t", 1)
res := new(http.ResponseWriter)
r.ServeHTTP(*res, req)
if _, ok := context.GetOk(req, "t"); ok {
t.Error("Context should have been cleared at end of request")
}
r.KeepContext = true
req, _ = http.NewRequest("GET", "http://localhost/", nil)
context.Set(req, "t", 1)
r.ServeHTTP(*res, req)
if _, ok := context.GetOk(req, "t"); !ok {
t.Error("Context should NOT have been cleared at end of request")
}
}
开发者ID:jboelter,项目名称:mux,代码行数:29,代码来源:mux_test.go
示例5: currentServicePipeID
func currentServicePipeID(r *http.Request) (string, string) {
var serviceID, pipeID string
if v, ok := context.GetOk(r, serviceIDKey); ok {
serviceID = v.(string)
}
if v, ok := context.GetOk(r, pipeIDKey); ok {
pipeID = v.(string)
}
return serviceID, pipeID
}
开发者ID:refiito,项目名称:pipes-api,代码行数:10,代码来源:request.go
示例6: GetFeatures
func GetFeatures(r *http.Request) map[string]interface{} {
result := map[string]interface{}{}
if features, ok := context.GetOk(r, "features"); ok {
result["features"] = features
}
if identifier, ok := context.GetOk(r, "api_key"); ok {
result["identifier"] = identifier
}
result["timestamp"] = time.Now().UTC().Format(time.RFC3339Nano)
return result
}
开发者ID:untoldone,项目名称:bloomapi,代码行数:15,代码来源:features.go
示例7: GetCallID
// GetCallID gets the current call ID (if any) from the request context.
func GetCallID(r *http.Request) (int64, bool) {
if v, present := context.GetOk(r, callID); present {
id, ok := v.(int64)
return id, ok
}
return 0, false
}
开发者ID:pombredanne,项目名称:appmon,代码行数:8,代码来源:call_id.go
示例8: contextGet
func contextGet(r *http.Request, key string) (interface{}, error) {
if val, ok := context.GetOk(r, key); ok {
return val, nil
}
return nil, errors.Errorf("no value exists in the context for key %q", key)
}
开发者ID:aerth,项目名称:cosgo,代码行数:7,代码来源:context_legacy.go
示例9: userContext
func userContext(r *http.Request) (*account.Account, bool) {
if user, ok := context.GetOk(r, userAccountKey); ok {
u, ok := user.(*account.Account)
return u, ok
}
return nil, false
}
开发者ID:decitrig,项目名称:innerhearth,代码行数:7,代码来源:context.go
示例10: HandleSnapshots
func HandleSnapshots(w http.ResponseWriter, r *http.Request) {
database, ok := context.GetOk(r, "DB")
if !ok {
RespondWithError(w, r, errors.New("Could'nt obtain database"), http.StatusInternalServerError)
return
}
db := database.(*mgo.Database)
params := r.URL.Query()
d := time.Now()
if date, ok := params["date"]; ok {
if t, err := time.Parse(timeLayout, date[0]); err == nil {
d = t
}
}
snapshot, err := hubspider.FindSnapshotByTime(db, d)
if err != nil {
if err == mgo.ErrNotFound {
RespondWithError(w, r, err, http.StatusNotFound)
return
}
RespondWithError(w, r, err, http.StatusInternalServerError)
return
}
snapshot.ServeJSON(w, r)
}
开发者ID:celrenheit,项目名称:trending-machine,代码行数:27,代码来源:snapshots.go
示例11: ServeHTTP
func (h *DBConn) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logger.Info.Println("Setting up the database connection")
_, ok := context.GetOk(r, consts.DB_KEY)
if ok {
errJson := `{"Error":"Internal Server Error"}`
logger.Error.Println("DBConnector middleware error. DB_KEY already set.")
http.Error(w, errJson, http.StatusInternalServerError)
return
}
//https://github.com/mattn/go-sqlite3/blob/master/_example/simple/simple.go
db, err := sql.Open("sqlite3", "./middleware-test.db")
if err != nil {
errJson := `{"Error":"Internal Server Error"}`
logger.Error.Println("DBConnector database connection problem. Check Logs.")
http.Error(w, errJson, http.StatusInternalServerError)
return
}
context.Set(r, consts.DB_KEY, db)
//Close database connection once middleware chain is complete
defer db.Close()
if h.next != nil {
h.next.ServeHTTP(w, r)
}
}
开发者ID:redsofa,项目名称:middleware-test,代码行数:30,代码来源:dbconn.go
示例12: main
func main() {
middle := interpose.New()
// Create a middleware that yields a global counter that increments until
// the server is shut down. Note that this would actually require a mutex
// or a channel to be safe for concurrent use. Therefore, this example is
// unsafe.
middle.Use(context.ClearHandler)
middle.Use(func() func(http.Handler) http.Handler {
c := 0
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
c++
context.Set(req, CountKey, c)
next.ServeHTTP(w, req)
})
}
}())
// Apply the router.
router := mux.NewRouter()
router.HandleFunc("/test/{user}", func(w http.ResponseWriter, req *http.Request) {
c, ok := context.GetOk(req, CountKey)
if !ok {
fmt.Println("Context not ok")
}
fmt.Fprintf(w, "Hi %s, this is visit #%d to the site since the server was last rebooted.", mux.Vars(req)["user"], c)
})
middle.UseHandler(router)
http.ListenAndServe(":3001", middle)
}
开发者ID:mvpmvh,项目名称:interpose,代码行数:35,代码来源:ascendinginteger.go
示例13: GetPost
// GetPost() returns binded Post from POST data
func GetPost(r *http.Request) (Post, error) {
rv, ok := context.GetOk(r, "post")
if !ok {
return Post{}, errors.New("context not set")
}
return rv.(Post), nil
}
开发者ID:intfrr,项目名称:vertigo,代码行数:8,代码来源:posts.go
示例14: HandleWith
//
// HandleWith() constructs a handler and inserts it into
// the mux router.
//
// It does the following to each request:
//
// Request Body JSON:
// - If blank, fills body with {}
// - Validates based on the schema provided
// (default: dozy.PresetJsonSchemaBlank)
//
// Query Strings:
// - Converts all query strings, except authtoken, to a
// map[string][]string
//
// Rate Limiting:
// - Handles rate limitng on requests with the authtoken in a
// URL query string called "authtoken"
// - Because it only rate handles requests with "authtoken,"
// it's especially important to use the .Query() function
// provided by gorilla/mux as much as possible
//
// Other:
// - Writes the data specified by the user's handler function,
// ensuring that only allowed HTTP response codes are used
// and that no response is sent on error
// - Sets the "Content-Type" header to "application/json"
// - Manages the LOCATION header on a dozy.StatusPostOk return
// value
// - Ensures that Content-Type from client is correct
//
// This method **must** be used with a dozy.ServeMux()-handled
// mux router. dozy.ServeMux() attaches some neccesary data
// values to the request, which are needed for the proper method
// of the HandleWith() and the HandleSpecialCost() functions. However,
// you can use a non dozy.HandleWith() method with the ServeMux()
// method, only loosing the functionality added with the HandleWith()
// method itself.
//
func (h handlerBuilder) HandleWith(method, path string, userHandler UserHandler) {
method = strings.ToUpper(method)
if (method == "GET" || method == "DELETE") && h.bodySchema != PresetJsonSchemaBlank {
panic("Method type " + method + " should not have a body set!")
}
builtHandler := func(rw http.ResponseWriter, req *http.Request) {
var cost uint
if h.customCost {
rawSettings, rawSettingsOk := context.GetOk(req, dozySettingsKey("settings"))
settings, settingsOk := rawSettings.(*Settings)
if !rawSettingsOk {
panic("rawSettings is *not* okay!")
}
if !settingsOk {
panic("settings is *not* okay!")
}
cost = settings.DefaultCost
} else {
cost = h.cost
}
handle(h.bodySchema, userHandler, cost, rw, req)
}
route := h.muxRouter.HandleFunc(path, builtHandler).Methods(method)
if len(h.queries) != 0 {
route.Queries(h.queries...)
}
}
开发者ID:hdiwan,项目名称:RedRoute,代码行数:71,代码来源:handle.go
示例15: Value
// Value returns Gorilla's context package's value for this Context's request
// and key. It delegates to the parent Context if there is no such value.
func (ctx *ctxWrapper) Value(key interface{}) interface{} {
if val, ok := gorillactx.GetOk(ctx.req, key); ok {
return val
}
return ctx.Context.Value(key)
}
开发者ID:kidstuff,项目名称:auth,代码行数:9,代码来源:auth.go
示例16: main
func main() {
mw := interpose.New()
// Set a random integer everytime someone loads the page
mw.Use(context.ClearHandler)
mw.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
c := rand.Int()
fmt.Println("Setting ctx count to:", c)
context.Set(req, CountKey, c)
next.ServeHTTP(w, req)
})
})
// Apply the router.
router := mux.NewRouter()
router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) {
c, ok := context.GetOk(req, CountKey)
if !ok {
fmt.Println("Get not ok")
}
fmt.Fprintf(w, "Welcome to the home page, %s!\nCount:%d", mux.Vars(req)["user"], c)
})
mw.UseHandler(router)
// Launch and permit graceful shutdown, allowing up to 10 seconds for existing
// connections to end
graceful.Run(":3001", 10*time.Second, mw)
}
开发者ID:mvpmvh,项目名称:interpose,代码行数:31,代码来源:main.go
示例17: iterateAddHeaders
// iterateAddHeaders is a helper functino that will iterate of a map and inject the key and value as a header in the request.
// if the key and value contain a tyk session variable reference, then it will try to inject the value
func (t *TransformHeaders) iterateAddHeaders(kv map[string]string, r *http.Request) {
// Get session data
ses, found := context.GetOk(r, SessionData)
var thisSessionState SessionState
if found {
thisSessionState = ses.(SessionState)
}
// Iterate and manage key array injection
for nKey, nVal := range kv {
if strings.Contains(nVal, TYK_META_LABEL) {
// Using meta_data key
log.Debug("Meta data key in use")
if found {
metaKey := strings.Replace(nVal, TYK_META_LABEL, "", 1)
if thisSessionState.MetaData != nil {
tempVal, ok := thisSessionState.MetaData.(map[string]interface{})[metaKey]
if ok {
nVal = tempVal.(string)
r.Header.Add(nKey, nVal)
} else {
log.Warning("Session Meta Data not found for key in map: ", metaKey)
}
} else {
log.Debug("Meta data object is nil! Skipping.")
}
}
} else {
r.Header.Add(nKey, nVal)
}
}
}
开发者ID:cppd245,项目名称:tyk,代码行数:36,代码来源:middleware_modify_headers.go
示例18: GetSettings
func GetSettings(r *http.Request) (Vertigo, error) {
rv, ok := context.GetOk(r, "settings")
if !ok {
return Vertigo{}, errors.New("context not set")
}
return rv.(Vertigo), nil
}
开发者ID:intfrr,项目名称:vertigo,代码行数:7,代码来源:settings.go
示例19: GetSearch
// GetSearch() returns binded Search from POST data
func GetSearch(r *http.Request) (Search, error) {
rv, ok := context.GetOk(r, "search")
if !ok {
return Search{}, errors.New("context not set")
}
return rv.(Search), nil
}
开发者ID:intfrr,项目名称:vertigo,代码行数:8,代码来源:posts.go
示例20: GetUser
func GetUser(r *http.Request) (User, error) {
rv, ok := context.GetOk(r, "user")
if !ok {
return User{}, errors.New("context not set")
}
return rv.(User), nil
}
开发者ID:intfrr,项目名称:vertigo,代码行数:7,代码来源:users.go
注:本文中的github.com/gorilla/context.GetOk函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论