本文整理汇总了Golang中github.com/ryanmoran/stack.Context.Set方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Set方法的具体用法?Golang Context.Set怎么用?Golang Context.Set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/ryanmoran/stack.Context
的用法示例。
在下文中一共展示了Context.Set方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServeHTTP
func (ware Authenticator) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) bool {
rawToken := ware.getToken(req)
if rawToken == "" {
return ware.Error(w, http.StatusUnauthorized, "Authorization header is invalid: missing")
}
token, err := jwt.Parse(rawToken, func(t *jwt.Token) (interface{}, error) {
return []byte(ware.UAAPublicKey), nil
})
if err != nil {
if strings.Contains(err.Error(), "expired") {
return ware.Error(w, http.StatusUnauthorized, "Authorization header is invalid: expired")
}
return ware.Error(w, http.StatusUnauthorized, "Authorization header is invalid: corrupt")
}
if !ware.containsATokenScope(w, token) {
return false
}
context.Set("token", token)
context.Set("client_id", token.Claims["client_id"])
return true
}
示例2: ServeHTTP
func (m Middleware) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) bool {
str := fmt.Sprintf("Middleware: %s\n", m.Name)
context.Set(m.Name, fmt.Sprintf("I'm a middleware %s\n", m.Name))
w.Header().Add("X-Middleware", m.Name)
w.Write([]byte(str))
return true
}
示例3: ServeHTTP
func (ware DatabaseAllocator) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) bool {
db := models.NewDatabase(ware.DB, models.Config{})
logger := gorpCompatibleLogger{
logger: context.Get("logger").(lager.Logger).WithData(lager.Data{
VCAPRequestIDKey: context.Get(VCAPRequestIDKey),
}),
}
if ware.Trace {
db.TraceOn("", logger)
}
context.Set("database", db)
return true
}
示例4: ServeHTTP
func (r RequestLogging) ServeHTTP(response http.ResponseWriter, request *http.Request, context stack.Context) bool {
requestID := request.Header.Get("X-Vcap-Request-Id")
if requestID == "" {
requestID = "UNKNOWN"
}
logSession := r.logger.Session("request", lager.Data{
VCAPRequestIDKey: requestID,
})
logSession.Info("incoming", lager.Data{
"method": request.Method,
"path": request.URL.Path,
})
context.Set("logger", logSession)
context.Set(VCAPRequestIDKey, requestID)
context.Set(RequestReceivedTime, time.Now().UTC())
return true
}
示例5:
handler senders.GetHandler
sendersCollection *mocks.SendersCollection
context stack.Context
writer *httptest.ResponseRecorder
request *http.Request
database *mocks.Database
conn *mocks.Connection
)
BeforeEach(func() {
conn = mocks.NewConnection()
database = mocks.NewDatabase()
database.ConnectionCall.Returns.Connection = conn
context = stack.NewContext()
context.Set("client_id", "some-client-id")
context.Set("database", database)
sendersCollection = mocks.NewSendersCollection()
sendersCollection.GetCall.Returns.Sender = collections.Sender{
ID: "some-sender-id",
Name: "some-sender",
}
writer = httptest.NewRecorder()
var err error
request, err = http.NewRequest("GET", "/senders/some-sender-id", nil)
Expect(err).NotTo(HaveOccurred())
handler = senders.NewGetHandler(sendersCollection)
示例6:
"scope": []string{"notification_preferences.read"},
}
request, err = http.NewRequest("GET", "/user_preferences", bytes.NewBuffer(body))
if err != nil {
panic(err)
}
token, err := jwt.Parse(helpers.BuildToken(tokenHeader, tokenClaims), func(token *jwt.Token) (interface{}, error) {
return []byte(application.UAAPublicKey), nil
})
database = mocks.NewDatabase()
context = stack.NewContext()
context.Set("token", token)
context.Set("database", database)
builder = services.NewPreferencesBuilder()
builder.Add(models.Preference{
ClientID: "raptorClient",
KindID: "hungry-kind",
Email: false,
})
builder.Add(models.Preference{
ClientID: "starWarsClient",
KindID: "vader-kind",
Email: true,
})
builder.GlobalUnsubscribe = true
示例7:
errorWriter *mocks.ErrorWriter
strategy *mocks.Strategy
)
BeforeEach(func() {
writer = httptest.NewRecorder()
request = &http.Request{URL: &url.URL{Path: "/uaa_scopes/great.scope"}}
strategy = mocks.NewStrategy()
errorWriter = mocks.NewErrorWriter()
connection = mocks.NewConnection()
database := mocks.NewDatabase()
database.ConnectionCall.Returns.Connection = connection
context = stack.NewContext()
context.Set("database", database)
context.Set(notify.VCAPRequestIDKey, "some-request-id")
notifyObj = mocks.NewNotify()
handler = notify.NewUAAScopeHandler(notifyObj, errorWriter, strategy)
})
Context("when the notifyObj.Execute returns a successful response", func() {
It("returns the JSON representation of the response", func() {
notifyObj.ExecuteCall.Returns.Response = []byte("whatever")
handler.ServeHTTP(writer, request, context)
Expect(writer.Code).To(Equal(http.StatusOK))
Expect(writer.Body.String()).To(Equal("whatever"))
})
示例8:
var err error
updater = mocks.NewTemplateUpdater()
errorWriter = mocks.NewErrorWriter()
writer = httptest.NewRecorder()
request, err = http.NewRequest("PUT", "/default_template", strings.NewReader(`{
"name": "Defaultish Template",
"subject": "{{.Subject}}",
"html": "<p>something</p>",
"text": "something",
"metadata": {"hello": true}
}`))
Expect(err).NotTo(HaveOccurred())
database = mocks.NewDatabase()
context = stack.NewContext()
context.Set("database", database)
handler = templates.NewUpdateDefaultHandler(updater, errorWriter)
})
It("updates the default template", func() {
handler.ServeHTTP(writer, request, context)
Expect(writer.Code).To(Equal(http.StatusNoContent))
Expect(updater.UpdateCall.Receives.Database).To(Equal(database))
Expect(updater.UpdateCall.Receives.TemplateID).To(Equal(models.DefaultTemplateID))
Expect(updater.UpdateCall.Receives.Template).To(Equal(models.Template{
Name: "Defaultish Template",
Subject: "{{.Subject}}",
HTML: "<p>something</p>",
Text: "something",
示例9:
BeforeEach(func() {
var err error
sqlDB, err = sqlmock.New()
Expect(err).NotTo(HaveOccurred())
ware = middleware.NewDatabaseAllocator(sqlDB, true)
writer = httptest.NewRecorder()
request = &http.Request{}
buffer = bytes.NewBuffer([]byte{})
logger := lager.NewLogger("notifications")
logger.RegisterSink(lager.NewWriterSink(buffer, lager.DEBUG))
context = stack.NewContext()
context.Set("logger", logger)
context.Set(middleware.VCAPRequestIDKey, "some-vcap-request-id")
})
AfterEach(func() {
err := sqlDB.Close()
Expect(err).NotTo(HaveOccurred())
})
It("allocates a database that it adds to the context", func() {
result := ware.ServeHTTP(writer, request, context)
Expect(result).To(BeTrue())
database, ok := context.Get("database").(*db.DB)
Expect(ok).To(BeTrue())
示例10:
request, err = http.NewRequest("POST", "/spaces/space-001", bytes.NewBuffer(body))
if err != nil {
panic(err)
}
request.Header.Set("Authorization", "Bearer "+rawToken)
token, err := jwt.Parse(rawToken, func(*jwt.Token) (interface{}, error) {
return []byte(application.UAAPublicKey), nil
})
database = mocks.NewDatabase()
reqReceivedTime, _ = time.Parse(time.RFC3339Nano, "2015-06-08T14:32:11.660762586-07:00")
context = stack.NewContext()
context.Set("token", token)
context.Set("database", database)
context.Set(notify.RequestReceivedTime, reqReceivedTime)
vcapRequestID = "some-request-id"
conn = mocks.NewConnection()
strategy = mocks.NewStrategy()
validator = mocks.NewValidator()
validator.ValidateCall.Returns.Valid = true
handler = notify.NewNotify(finder, registrar)
})
It("delegates to the strategy", func() {
_, err := handler.Execute(conn, request, context, "space-001", strategy, validator, vcapRequestID)
示例11:
var (
handler campaigntypes.UpdateHandler
campaignTypesCollection *mocks.CampaignTypesCollection
context stack.Context
writer *httptest.ResponseRecorder
request *http.Request
database *mocks.Database
tokenHeader map[string]interface{}
tokenClaims map[string]interface{}
guid string
)
BeforeEach(func() {
context = stack.NewContext()
context.Set("client_id", "some-client-id")
database = mocks.NewDatabase()
context.Set("database", database)
tokenHeader = map[string]interface{}{
"alg": "FAST",
}
tokenClaims = map[string]interface{}{
"client_id": "some-uaa-client-id",
"exp": int64(3404281214),
"scope": []string{
"notifications.write",
"critical_notifications.write",
},
}
示例12:
handler senders.ListHandler
sendersCollection *mocks.SendersCollection
context stack.Context
writer *httptest.ResponseRecorder
request *http.Request
conn *mocks.Connection
database *mocks.Database
)
BeforeEach(func() {
conn = mocks.NewConnection()
database = mocks.NewDatabase()
database.ConnectionCall.Returns.Connection = conn
context = stack.NewContext()
context.Set("client_id", "whatever")
context.Set("database", database)
sendersCollection = mocks.NewSendersCollection()
sendersList := []collections.Sender{
{
ID: "sender-id-one",
Name: "first sender",
},
{
ID: "sender-id-two",
Name: "second sender",
},
}
sendersCollection.ListCall.Returns.SenderList = sendersList