当前位置: 首页>>代码示例>>Golang>>正文


Golang context.Get函数代码示例

本文整理汇总了Golang中github.com/gorilla/context.Get函数的典型用法代码示例。如果您正苦于以下问题:Golang Get函数的具体用法?Golang Get怎么用?Golang Get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Get函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: WebThingProgram

func WebThingProgram(w http.ResponseWriter, r *http.Request) {
	thing := context.Get(r, ContextKeyThing).(*Thing)
	account := context.Get(r, ContextKeyAccount).(*Account)

	if !thing.EditableById(account.Character) {
		http.Error(w, "No access to program", http.StatusForbidden)
		return
	}

	var newProgram *ThingProgram
	if r.Method == "POST" {
		program := r.PostFormValue("text")

		newProgram = NewProgram(program)
		if newProgram.Error == nil {
			thing.Program = newProgram
			World.SaveThing(thing)

			http.Redirect(w, r, fmt.Sprintf("%sprogram", thing.GetURL()), http.StatusSeeOther)
			return
		}
	}

	RenderTemplate(w, r, "thing/page/program.html", map[string]interface{}{
		"IncludeCodeMirror": true,
		"Title":             fmt.Sprintf("Edit program – %s", thing.Name),
		"Thing":             thing,
		"Program":           newProgram,
	})
}
开发者ID:natmeox,项目名称:mess,代码行数:30,代码来源:web.go

示例2: ServeHTTP

// ServeHTTP will store the request details in the analytics store if necessary and proxy the request to it's
// final destination, this is invoked by the ProxyHandler or right at the start of a request chain if the URL
// Spec states the path is Ignored
func (s SuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	// Make sure we get the correct target URL
	if s.Spec.APIDefinition.Proxy.StripListenPath {
		r.URL.Path = strings.Replace(r.URL.Path, s.Spec.Proxy.ListenPath, "", 1)
	}

	if config.EnableAnalytics {
		t := time.Now()

		// Track the key ID if it exists
		authHeaderValue := context.Get(r, AuthHeaderValue)
		keyName := ""
		if authHeaderValue != nil {
			keyName = authHeaderValue.(string)
		}

		// Track version data
		version := s.Spec.getVersionFromRequest(r)
		if version == "" {
			version = "Non Versioned"
		}

		// If OAuth, we need to grab it from the session, which may or may not exist
		OauthClientID := ""
		thisSessionState := context.Get(r, SessionData)

		if thisSessionState != nil {
			OauthClientID = thisSessionState.(SessionState).OauthClientID
		}

		thisRecord := AnalyticsRecord{
			r.Method,
			r.URL.Path,
			r.ContentLength,
			r.Header.Get("User-Agent"),
			t.Day(),
			t.Month(),
			t.Year(),
			t.Hour(),
			200,
			keyName,
			t,
			version,
			s.Spec.APIDefinition.Name,
			s.Spec.APIDefinition.APIID,
			s.Spec.APIDefinition.OrgID,
			OauthClientID}

		go analytics.RecordHit(thisRecord)
	}

	s.Proxy.ServeHTTP(w, r)

	if doMemoryProfile {
		pprof.WriteHeapProfile(profileFile)
	}

	context.Clear(r)
}
开发者ID:joshrendek,项目名称:tyk,代码行数:63,代码来源:handler_success.go

示例3: HandleError

// HandleError is the actual error handler and will store the error details in analytics if analytics processing is enabled.
func (e ErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, err string, errCode int) {
	if config.EnableAnalytics {
		t := time.Now()

		// Track the key ID if it exists
		authHeaderValue := context.Get(r, AuthHeaderValue)
		keyName := ""
		if authHeaderValue != nil {
			keyName = authHeaderValue.(string)
		}

		version := e.Spec.getVersionFromRequest(r)
		if version == "" {
			version = "Non Versioned"
		}

		if e.TykMiddleware.Spec.APIDefinition.Proxy.StripListenPath {
			r.URL.Path = strings.Replace(r.URL.Path, e.TykMiddleware.Spec.Proxy.ListenPath, "", 1)
		}

		OauthClientID := ""
		thisSessionState := context.Get(r, SessionData)

		if thisSessionState != nil {
			OauthClientID = thisSessionState.(SessionState).OauthClientID
		}

		thisRecord := AnalyticsRecord{
			r.Method,
			r.URL.Path,
			r.ContentLength,
			r.Header.Get("User-Agent"),
			t.Day(),
			t.Month(),
			t.Year(),
			t.Hour(),
			errCode,
			keyName,
			t,
			version,
			e.Spec.APIDefinition.Name,
			e.Spec.APIDefinition.APIID,
			e.Spec.APIDefinition.OrgID,
			OauthClientID}
		go analytics.RecordHit(thisRecord)
	}

	w.Header().Add("Content-Type", "application/json")
	w.Header().Add("X-Generator", "tyk.io")
	log.Debug("Returning error header")
	w.WriteHeader(errCode)
	thisError := APIError{fmt.Sprintf("%s", err)}
	templates.ExecuteTemplate(w, "error.json", &thisError)
	if doMemoryProfile {
		pprof.WriteHeapProfile(profileFile)
	}

	// Clean up
	context.Clear(r)
}
开发者ID:alexpopero,项目名称:tyk,代码行数:61,代码来源:handler_error.go

示例4: PostAccessTokens

func PostAccessTokens(w http.ResponseWriter, r *http.Request) {
	db := context.Get(r, "db").(*sqlx.DB)

	cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore)

	session, _ := cookieStore.Get(r, "resourcedmaster-session")

	currentUser := session.Values["user"].(*dal.UserRow)

	clusterID, err := getIdFromPath(w, r)
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	level := r.FormValue("Level")

	_, err = dal.NewAccessToken(db).Create(nil, currentUser.ID, clusterID, level)
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	http.Redirect(w, r, "/clusters", 301)
}
开发者ID:simudream,项目名称:resourced-master,代码行数:25,代码来源:access_tokens.go

示例5: PostClustersCurrent

func PostClustersCurrent(w http.ResponseWriter, r *http.Request) {
	cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore)

	session, _ := cookieStore.Get(r, "resourcedmaster-session")

	redirectPath := "/"

	recentRequestPathInterface := session.Values["recentRequestPath"]
	if recentRequestPathInterface != nil {
		redirectPath = recentRequestPathInterface.(string)
	}

	clusterIDString := r.FormValue("ClusterID")
	clusterID, err := strconv.ParseInt(clusterIDString, 10, 64)
	if err != nil {
		http.Redirect(w, r, redirectPath, 301)
		return
	}

	clusterRows := context.Get(r, "clusters").([]*dal.ClusterRow)
	for _, clusterRow := range clusterRows {
		if clusterRow.ID == clusterID {
			session.Values["currentCluster"] = clusterRow

			err := session.Save(r, w)
			if err != nil {
				libhttp.HandleErrorJson(w, err)
				return
			}
			break
		}
	}

	http.Redirect(w, r, redirectPath, 301)
}
开发者ID:simudream,项目名称:resourced-master,代码行数:35,代码来源:clusters.go

示例6: PostApiHosts

func PostApiHosts(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	db := context.Get(r, "db").(*sqlx.DB)

	accessTokenRow := context.Get(r, "accessTokenRow").(*dal.AccessTokenRow)

	dataJson, err := ioutil.ReadAll(r.Body)
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	hostRow, err := dal.NewHost(db).CreateOrUpdate(nil, accessTokenRow, dataJson)
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	hostRowJson, err := json.Marshal(hostRow)
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	w.Write(hostRowJson)
}
开发者ID:simudream,项目名称:resourced-master,代码行数:27,代码来源:hosts.go

示例7: API_SMTP

// API_SMTP handles requests for the /api/smtp/ endpoint
func API_SMTP(w http.ResponseWriter, r *http.Request) {
	switch {
	case r.Method == "GET":
		ss, err := models.GetSMTPs(ctx.Get(r, "user_id").(int64))
		if err != nil {
			Logger.Println(err)
		}
		JSONResponse(w, ss, http.StatusOK)
	//POST: Create a new SMTP and return it as JSON
	case r.Method == "POST":
		s := models.SMTP{}
		// Put the request into a page
		err := json.NewDecoder(r.Body).Decode(&s)
		if err != nil {
			JSONResponse(w, models.Response{Success: false, Message: "Invalid request"}, http.StatusBadRequest)
			return
		}
		// Check to make sure the name is unique
		_, err = models.GetSMTPByName(s.Name, ctx.Get(r, "user_id").(int64))
		if err != gorm.ErrRecordNotFound {
			JSONResponse(w, models.Response{Success: false, Message: "SMTP name already in use"}, http.StatusConflict)
			Logger.Println(err)
			return
		}
		s.ModifiedDate = time.Now()
		s.UserId = ctx.Get(r, "user_id").(int64)
		err = models.PostSMTP(&s)
		if err != nil {
			JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusInternalServerError)
			return
		}
		JSONResponse(w, s, http.StatusCreated)
	}
}
开发者ID:TheBigBear,项目名称:gophish,代码行数:35,代码来源:api.go

示例8: newReviewHandler

func (c *appContext) newReviewHandler(w http.ResponseWriter, r *http.Request) {

	user, err := userget(r)
	if err != nil {
		log.Println(err)
	}

	repo := ReviewRepo{c.db.C("reviews")}
	params := context.Get(r, "params").(httprouter.Params)
	skillslug := params.ByName("slug")
	body := context.Get(r, "body").(*ReviewResource)
	log.Println(skillslug)

	body.Data.SkillSlug = skillslug
	body.Data.Username = user.Username
	err = repo.Create(&body.Data)
	if err != nil {
		log.Println(err)
	}

	c.newReviewFeed(&body.Data)
	w.Header().Set("Content-Type", "application/vnd.api+json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(body)
}
开发者ID:ifactory-ng,项目名称:oddjobz-backend,代码行数:25,代码来源:reviews.go

示例9: New

// New creates a new HttpHandler for the alice middleware package
func (k KeyExpired) New() func(http.Handler) http.Handler {
	aliceHandler := func(h http.Handler) http.Handler {
		thisHandler := func(w http.ResponseWriter, r *http.Request) {

			thisSessionState := context.Get(r, SessionData).(SessionState)
			authHeaderValue := context.Get(r, AuthHeaderValue).(string)
			keyExpired := authManager.IsKeyExpired(&thisSessionState)

			if keyExpired {
				log.WithFields(logrus.Fields{
					"path":   r.URL.Path,
					"origin": r.RemoteAddr,
					"key":    authHeaderValue,
				}).Info("Attempted access from expired key.")
				handler := ErrorHandler{k.TykMiddleware}
				handler.HandleError(w, r, "Key has expired, please renew", 403)
				return
			}

			// Request is valid, carry on
			h.ServeHTTP(w, r)
		}

		return http.HandlerFunc(thisHandler)
	}

	return aliceHandler
}
开发者ID:joshrendek,项目名称:tyk,代码行数:29,代码来源:middleware_key_expired_check.go

示例10: RefreshToken

func RefreshToken(w http.ResponseWriter, r *http.Request) {
	userID := context.Get(r, "user_id").(uint64)
	token := context.Get(r, "user_token").(string)
	var reqBody authorizePutBody
	if appErr := decode(r, &reqBody); appErr != nil {
		reply.Err(w, appErr)
		return
	}
	userToken := model.UserToken{UserID: userID, Token: token, RefreshToken: reqBody.RefreshToken}
	if valid, err := userToken.RefreshTokenValid(); !valid || err != nil {
		if !valid {
			reply.Err(w, ae.TokenInvalid("", err, "refresh_token"))
		} else {
			reply.Err(w, ae.DB("", err))
		}
		return
	}
	if err := userToken.Delete(); err != nil {
		reply.Err(w, ae.DB("", err))
		return
	}
	newToken := model.UserToken{UserID: userID}
	if err := newToken.Add(); err != nil {
		reply.Err(w, ae.DB("", err))
		return
	}
	reply.OK(w, newToken)
}
开发者ID:kalorieapp,项目名称:kalorie_backend,代码行数:28,代码来源:user.go

示例11: FilterIfOwnerRelations

func FilterIfOwnerRelations(r *http.Request, filter *usecases.Filter) *usecases.Filter {
	ownerRelationsCtx := context.Get(r, "ownerRelations")
	if ownerRelationsCtx != nil {
		currentSession := context.Get(r, "currentSession").(domain.Session)

		idKey := "accountId"

		if context.Get(r, "resource").(string) == "accounts" {
			idKey = "id"
		}

		if filter == nil {
			filter = &usecases.Filter{
				Where: map[string]interface{}{idKey: currentSession.AccountID},
			}
		} else {
			if filter.Where == nil {
				filter.Where = map[string]interface{}{idKey: currentSession.AccountID}
			} else {
				filter.Where[idKey] = currentSession.AccountID
			}
		}
	}

	return filter
}
开发者ID:optimuse,项目名称:zest,代码行数:26,代码来源:utils.go

示例12: API_Groups

// API_Groups returns details about the requested group. If the campaign is not
// valid, API_Groups returns null.
func API_Groups(w http.ResponseWriter, r *http.Request) {
	switch {
	case r.Method == "GET":
		gs, err := models.GetGroups(ctx.Get(r, "user_id").(int64))
		if err != nil {
			JSONResponse(w, models.Response{Success: false, Message: "No groups found"}, http.StatusNotFound)
			return
		}
		JSONResponse(w, gs, http.StatusOK)
	//POST: Create a new group and return it as JSON
	case r.Method == "POST":
		g := models.Group{}
		// Put the request into a group
		err := json.NewDecoder(r.Body).Decode(&g)
		if err != nil {
			JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest)
			return
		}
		_, err = models.GetGroupByName(g.Name, ctx.Get(r, "user_id").(int64))
		if err != gorm.RecordNotFound {
			JSONResponse(w, models.Response{Success: false, Message: "Group name already in use"}, http.StatusConflict)
			return
		}
		g.ModifiedDate = time.Now()
		g.UserId = ctx.Get(r, "user_id").(int64)
		err = models.PostGroup(&g)
		if err != nil {
			JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest)
			return
		}
		w.Header().Set("Location", "http://localhost:3333/api/groups/"+string(g.Id))
		JSONResponse(w, g, http.StatusCreated)
	}
}
开发者ID:tohitsugu,项目名称:gophish,代码行数:36,代码来源:api.go

示例13: PostMetadata

func PostMetadata(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")

	cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore)

	session, _ := cookieStore.Get(r, "resourcedmaster-session")

	currentClusterInterface := session.Values["currentCluster"]
	if currentClusterInterface == nil {
		http.Redirect(w, r, "/", 301)
		return
	}
	currentCluster := currentClusterInterface.(*dal.ClusterRow)

	key := r.FormValue("Key")
	data := r.FormValue("Data")

	db := context.Get(r, "db").(*sqlx.DB)

	_, err := dal.NewMetadata(db).CreateOrUpdate(nil, currentCluster.ID, key, []byte(data))
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	http.Redirect(w, r, "/metadata", 301)
}
开发者ID:simudream,项目名称:resourced-master,代码行数:27,代码来源:metadata.go

示例14: PostLogin

// PostLogin performs login.
func PostLogin(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")

	db := context.Get(r, "db").(*sqlx.DB)
	cookieStore := context.Get(r, "cookieStore").(*sessions.CookieStore)

	email := r.FormValue("Email")
	password := r.FormValue("Password")

	u := models.NewUser(db)

	user, err := u.GetUserByEmailAndPassword(nil, email, password)
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	session, _ := cookieStore.Get(r, "$GO_BOOTSTRAP_PROJECT_NAME-session")
	session.Values["user"] = user

	err = session.Save(r, w)
	if err != nil {
		libhttp.HandleErrorJson(w, err)
		return
	}

	http.Redirect(w, r, "/", 302)
}
开发者ID:tjyang,项目名称:go-bootstrap,代码行数:29,代码来源:users.go

示例15: API_Campaigns

// API_Campaigns returns a list of campaigns if requested via GET.
// If requested via POST, API_Campaigns creates a new campaign and returns a reference to it.
func API_Campaigns(w http.ResponseWriter, r *http.Request) {
	switch {
	case r.Method == "GET":
		cs, err := models.GetCampaigns(ctx.Get(r, "user_id").(int64))
		if err != nil {
			fmt.Println(err)
		}
		JSONResponse(w, cs, http.StatusOK)
	//POST: Create a new campaign and return it as JSON
	case r.Method == "POST":
		c := models.Campaign{}
		// Put the request into a campaign
		err := json.NewDecoder(r.Body).Decode(&c)
		if err != nil {
			JSONResponse(w, models.Response{Success: false, Message: "Invalid JSON structure"}, http.StatusBadRequest)
			return
		}
		err = models.PostCampaign(&c, ctx.Get(r, "user_id").(int64))
		if err != nil {
			JSONResponse(w, models.Response{Success: false, Message: err.Error()}, http.StatusBadRequest)
			return
		}
		Worker.Queue <- &c
		JSONResponse(w, c, http.StatusCreated)
	}
}
开发者ID:tohitsugu,项目名称:gophish,代码行数:28,代码来源:api.go


注:本文中的github.com/gorilla/context.Get函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。