本文整理汇总了Golang中github.com/ryanmoran/stack.Context类的典型用法代码示例。如果您正苦于以下问题:Golang Context类的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServeHTTP
func (h DeleteHandler) ServeHTTP(w http.ResponseWriter, request *http.Request, context stack.Context) {
splitURL := strings.Split(request.URL.Path, "/")
templateID := splitURL[len(splitURL)-1]
database := context.Get("database").(collections.DatabaseInterface)
clientID := context.Get("client_id").(string)
_, err := h.deleter.Get(database.Connection(), templateID, clientID)
if err != nil {
switch err.(type) {
case collections.NotFoundError:
w.WriteHeader(http.StatusNotFound)
default:
w.WriteHeader(http.StatusInternalServerError)
}
fmt.Fprintf(w, `{"errors": [%q]}`, err)
return
}
err = h.deleter.Delete(database.Connection(), templateID)
if err != nil {
switch err.(type) {
case collections.NotFoundError:
w.WriteHeader(http.StatusNotFound)
default:
w.WriteHeader(http.StatusInternalServerError)
}
fmt.Fprintf(w, `{"errors": [%q]}`, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
示例2: ServeHTTP
func (h GetHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
templateID := strings.Split(req.URL.Path, "/templates/")[1]
template, err := h.finder.FindByID(context.Get("database").(DatabaseInterface), templateID)
if err != nil {
h.errorWriter.Write(w, err)
return
}
var metadata map[string]interface{}
err = json.Unmarshal([]byte(template.Metadata), &metadata)
if err != nil {
h.errorWriter.Write(w, err)
return
}
templateOutput := TemplateOutput{
Name: template.Name,
Subject: template.Subject,
HTML: template.HTML,
Text: template.Text,
Metadata: metadata,
}
writeJSON(w, http.StatusOK, templateOutput)
}
示例3: ServeHTTP
func (h ListHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request, context stack.Context) {
clientID := context.Get("client_id").(string)
database := context.Get("database").(DatabaseInterface)
senderList, err := h.collection.List(database.Connection(), clientID)
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, `{ "errors": [ %q ] }`, err)
return
}
responseList := []interface{}{}
for _, sender := range senderList {
responseList = append(responseList, map[string]interface{}{
"id": sender.ID,
"name": sender.Name,
})
}
listResponse, _ := json.Marshal(map[string]interface{}{
"senders": responseList,
})
writer.Write(listResponse)
}
示例4: 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
}
示例5: ServeHTTP
func (h GetHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
splitURL := strings.Split(req.URL.Path, "/")
senderID := splitURL[len(splitURL)-3]
campaignID := splitURL[len(splitURL)-1]
clientID := context.Get("client_id").(string)
database := context.Get("database").(collections.DatabaseInterface)
campaign, err := h.campaigns.Get(database.Connection(), campaignID, senderID, clientID)
if err != nil {
switch err.(type) {
case collections.NotFoundError:
w.WriteHeader(http.StatusNotFound)
default:
w.WriteHeader(http.StatusInternalServerError)
}
fmt.Fprintf(w, `{ "errors": [%q] }`, err)
return
}
getResponse, _ := json.Marshal(map[string]interface{}{
"id": campaign.ID,
"send_to": campaign.SendTo,
"campaign_type_id": campaign.CampaignTypeID,
"text": campaign.Text,
"html": campaign.HTML,
"subject": campaign.Subject,
"template_id": campaign.TemplateID,
"reply_to": campaign.ReplyTo,
})
w.Write(getResponse)
}
示例6: 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
}
示例7: ServeHTTP
func (h ListHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
templates, err := h.lister.List(context.Get("database").(DatabaseInterface))
if err != nil {
h.errorWriter.Write(w, err)
return
}
writeJSON(w, http.StatusOK, templates)
}
示例8: ServeHTTP
func (h RegistrationHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
database := context.Get("database").(DatabaseInterface)
connection := database.Connection()
parameters, err := NewRegistrationParams(req.Body)
if err != nil {
h.errorWriter.Write(w, err)
return
}
err = parameters.Validate()
if err != nil {
h.errorWriter.Write(w, err)
return
}
token := context.Get("token").(*jwt.Token)
clientID := token.Claims["client_id"].(string)
client := models.Client{
ID: clientID,
Description: parameters.SourceDescription,
}
kinds, err := h.ValidateCriticalScopes(token.Claims["scope"], parameters.Kinds, client)
if err != nil {
h.errorWriter.Write(w, err)
return
}
transaction := connection.Transaction()
transaction.Begin()
err = h.registrar.Register(transaction, client, kinds)
if err != nil {
transaction.Rollback()
h.errorWriter.Write(w, err)
return
}
if parameters.IncludesKinds {
err = h.registrar.Prune(transaction, client, kinds)
if err != nil {
transaction.Rollback()
h.errorWriter.Write(w, err)
return
}
}
err = transaction.Commit()
if err != nil {
h.errorWriter.Write(w, err)
return
}
}
示例9: ServeHTTP
func (h DeleteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
templateID := strings.Split(req.URL.Path, "/templates/")[1]
err := h.deleter.Delete(context.Get("database").(DatabaseInterface), templateID)
if err != nil {
h.errorWriter.Write(w, err)
}
w.WriteHeader(http.StatusNoContent)
}
示例10: ServeHTTP
func (h ShowHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request, context stack.Context) {
splitURL := strings.Split(request.URL.Path, "/")
campaignTypeID := splitURL[len(splitURL)-1]
senderID := splitURL[len(splitURL)-3]
if senderID == "" {
writer.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(writer, `{"errors": [%q]}`, "missing sender id")
return
}
if campaignTypeID == "" {
headers := writer.Header()
headers.Set("Location", fmt.Sprintf("/senders/%s/campaign_types", senderID))
writer.WriteHeader(http.StatusMovedPermanently)
return
}
clientID := context.Get("client_id")
if clientID == "" {
writer.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(writer, `{"errors": [%q]}`, "missing client id")
return
}
database := context.Get("database").(DatabaseInterface)
campaignType, err := h.collection.Get(database.Connection(), campaignTypeID, senderID, context.Get("client_id").(string))
if err != nil {
switch err.(type) {
case collections.NotFoundError:
writer.WriteHeader(http.StatusNotFound)
default:
writer.WriteHeader(http.StatusInternalServerError)
}
fmt.Fprintf(writer, `{"errors": [%q]}`, err)
return
}
jsonMap := map[string]interface{}{
"id": campaignType.ID,
"name": campaignType.Name,
"description": campaignType.Description,
"critical": campaignType.Critical,
"template_id": campaignType.TemplateID,
}
jsonBody, err := json.Marshal(jsonMap)
if err != nil {
panic(err)
}
writer.Write([]byte(jsonBody))
}
示例11: ServeHTTP
func (h GetUserPreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
userGUID := strings.TrimPrefix(req.URL.Path, "/user_preferences/")
parsed, err := h.preferences.Find(context.Get("database").(DatabaseInterface), userGUID)
if err != nil {
h.errorWriter.Write(w, err)
return
}
writeJSON(w, http.StatusOK, parsed)
}
示例12: ServeHTTP
func (h ListAssociationsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
templateID := h.parseTemplateID(req.URL.Path)
associations, err := h.lister.List(context.Get("database").(DatabaseInterface), templateID)
if err != nil {
h.errorWriter.Write(w, err)
return
}
templateAssociationsDocument := h.mapToJSON(associations)
writeJSON(w, http.StatusOK, templateAssociationsDocument)
}
示例13: ServeHTTP
func (h UpdateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
splitURL := strings.Split(req.URL.Path, "/")
senderID := splitURL[len(splitURL)-1]
var updateRequest struct {
Name string `json:"name"`
}
err := json.NewDecoder(req.Body).Decode(&updateRequest)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"errors": ["invalid json body"]}`))
return
}
database := context.Get("database").(DatabaseInterface)
clientID := context.Get("client_id").(string)
_, err = h.senders.Get(database.Connection(), senderID, clientID)
if err != nil {
switch err.(type) {
case collections.NotFoundError:
w.WriteHeader(http.StatusNotFound)
default:
w.WriteHeader(http.StatusInternalServerError)
}
w.Write([]byte(fmt.Sprintf(`{ "errors": [ %q ]}`, err)))
return
}
sender, err := h.senders.Set(database.Connection(), collections.Sender{
ID: senderID,
Name: updateRequest.Name,
ClientID: clientID,
})
if err != nil {
switch err.(type) {
case collections.DuplicateRecordError:
w.WriteHeader(422)
default:
w.WriteHeader(http.StatusInternalServerError)
}
w.Write([]byte(fmt.Sprintf(`{ "errors": [ %q ]}`, err)))
return
}
updateResponse, _ := json.Marshal(map[string]string{
"id": sender.ID,
"name": sender.Name,
})
w.Write(updateResponse)
}
示例14: ServeHTTP
func (h EveryoneHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
connection := context.Get("database").(DatabaseInterface).Connection()
vcapRequestID := context.Get(VCAPRequestIDKey).(string)
output, err := h.notify.Execute(connection, req, context, "", h.strategy, GUIDValidator{}, vcapRequestID)
if err != nil {
h.errorWriter.Write(w, err)
return
}
w.WriteHeader(http.StatusOK)
w.Write(output)
}
示例15: ServeHTTP
func (h UpdatePreferencesHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
database := context.Get("database").(DatabaseInterface)
connection := database.Connection()
token := context.Get("token").(*jwt.Token)
if _, ok := token.Claims["user_id"]; !ok {
h.errorWriter.Write(w, webutil.MissingUserTokenError("Missing user_id from token claims."))
return
}
userID := token.Claims["user_id"].(string)
builder := services.NewPreferencesBuilder()
validator := valiant.NewValidator(req.Body)
err := validator.Validate(&builder)
if err != nil {
h.errorWriter.Write(w, webutil.ValidationError([]string{err.Error()}))
return
}
preferences, err := builder.ToPreferences()
if err != nil {
h.errorWriter.Write(w, webutil.ValidationError([]string{err.Error()}))
return
}
transaction := connection.Transaction()
transaction.Begin()
err = h.preferences.Update(transaction, preferences, builder.GlobalUnsubscribe, userID)
if err != nil {
transaction.Rollback()
switch err.(type) {
case services.MissingKindOrClientError, services.CriticalKindError:
h.errorWriter.Write(w, webutil.ValidationError([]string{err.Error()}))
default:
h.errorWriter.Write(w, err)
}
return
}
err = transaction.Commit()
if err != nil {
h.errorWriter.Write(w, models.NewTransactionCommitError(err.Error()))
return
}
w.WriteHeader(http.StatusNoContent)
}