本文整理汇总了Golang中net/http.Redirect函数的典型用法代码示例。如果您正苦于以下问题:Golang Redirect函数的具体用法?Golang Redirect怎么用?Golang Redirect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Redirect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: postLogin
func postLogin(w http.ResponseWriter, r *http.Request, c *web.Context) {
email, password := r.FormValue("email"), r.FormValue("password")
user, ok := GetUser(email, password)
if !ok || (user.Role != "employee" && user.Role != "admin") {
c.SetFlash("alertError", "Incorrect email or password")
http.Redirect(w, r, "/login", 303)
return
}
employee, ok := GetEmployee(user.Id)
if !ok {
c.SetFlash("alertError", "Error finding user")
http.Redirect(w, r, "/login", 303)
return
}
c.Login(user.Role)
c.SetSession(map[string]interface{}{
"emplyeeId": employee.Id,
"email": employee.Email,
})
if user.Role == "employee" {
http.Redirect(w, r, "/employee/home", 303)
return
}
if user.Role == "admin" {
http.Redirect(w, r, "/admin/home", 303)
return
}
return
}
示例2: DoSignup
// Processes for data for signup and sends email to verify account
func DoSignup(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
vKey := make([]byte, 32)
n, err := rand.Read(vKey)
if n != len(vKey) || err != nil {
log.Println("Could not successfully read from the system CSPRNG.")
}
validationKey := hex.EncodeToString(vKey)
stmt, _ := db.Prepare("insert into signup(username, email, password, validationKey) values(?,?,?,?)")
_, err = stmt.Exec(r.FormValue("username"), r.FormValue("email"), r.FormValue("password"), validationKey)
if err != nil {
// if a validation requests already exists resend email
if strings.Contains(err.Error(), "1062") {
log.Println("1062 error")
stmt, _ := db.Prepare("select validationKey from signup where username=?")
res := stmt.QueryRow(r.FormValue("username"))
res.Scan(&validationKey)
sendVerification(r.FormValue("email"), validationKey)
http.Redirect(w, r, r.URL.Host+"/resendValidation", 302)
} else {
log.Print("Error creating signup record")
log.Println(err)
}
} else {
sendVerification(r.FormValue("email"), validationKey)
http.Redirect(w, r, r.URL.Host+"/validationSent", 302)
}
}
示例3: ServeHTTP
func (h handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if session.Store == nil {
// server should not be started until Store is set!
panic(session.ErrNoStore)
}
// login page should be allowed
if req.URL.Path == LoginPage {
h.Handler.ServeHTTP(rw, req)
return
}
// check the cookie existance
s, err := session.Store.Get(req)
if err != nil {
http.Redirect(rw, req, LoginPage+"?from="+url.QueryEscape(req.URL.String()), http.StatusFound)
return
}
// check for cookie expiration
if s.Expires.Before(time.Now()) {
if err = session.Store.Del(req, rw); err != nil {
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
http.Redirect(rw, req, LoginPage+"?from="+url.QueryEscape(req.URL.String()), http.StatusTemporaryRedirect)
return
}
// refresh expiration and store new cookie
s.Expires = time.Now().Add(session.MaxAge)
session.Store.Put(req, rw, *s)
h.Handler.ServeHTTP(rw, req)
}
示例4: login
func login(c *api.Context, w http.ResponseWriter, r *http.Request) {
if !CheckBrowserCompatability(c, r) {
return
}
params := mux.Vars(r)
teamName := params["team"]
var team *model.Team
if tResult := <-api.Srv.Store.Team().GetByName(teamName); tResult.Err != nil {
l4g.Error("Couldn't find team name=%v, teamURL=%v, err=%v", teamName, c.GetTeamURL(), tResult.Err.Message)
http.Redirect(w, r, api.GetProtocol(r)+"://"+r.Host, http.StatusTemporaryRedirect)
return
} else {
team = tResult.Data.(*model.Team)
}
// If we are already logged into this team then go to home
if len(c.Session.UserId) != 0 && c.Session.TeamId == team.Id {
page := NewHtmlTemplatePage("home", "Home")
page.Props["TeamURL"] = c.GetTeamURL()
page.Render(c, w)
return
}
// We still might be able to switch to this team because we've logged in before
if multiCookie, err := r.Cookie(model.MULTI_SESSION_TOKEN); err == nil {
multiToken := multiCookie.Value
if len(multiToken) > 0 {
tokens := strings.Split(multiToken, " ")
for _, token := range tokens {
if sr := <-api.Srv.Store.Session().Get(token); sr.Err == nil {
s := sr.Data.(*model.Session)
if !s.IsExpired() && s.TeamId == team.Id {
w.Header().Set(model.HEADER_TOKEN, s.Token)
sessionCookie := &http.Cookie{
Name: model.SESSION_TOKEN,
Value: s.Token,
Path: "/",
MaxAge: model.SESSION_TIME_WEB_IN_SECS,
HttpOnly: true,
}
http.SetCookie(w, sessionCookie)
http.Redirect(w, r, c.GetSiteURL()+"/"+team.Name+"/channels/town-square", http.StatusTemporaryRedirect)
return
}
}
}
}
}
page := NewHtmlTemplatePage("login", "Login")
page.Props["TeamDisplayName"] = team.DisplayName
page.Props["TeamName"] = team.Name
page.Render(c, w)
}
示例5: index
func index(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
id := getID(res, req)
if req.Method == "POST" {
src, _, err := req.FormFile("data")
if err != nil {
log.Errorf(ctx, "ERROR index req.FormFile: %s", err)
// TODO: create error page to show user
http.Redirect(res, req, "/", http.StatusSeeOther)
return
}
err = uploadPhoto(src, id, req)
if err != nil {
log.Errorf(ctx, "ERROR index uploadPhoto: %s", err)
// expired cookie may exist on client
http.Redirect(res, req, "/logout", http.StatusSeeOther)
return
}
}
m, err := retrieveMemc(id, req)
if err != nil {
log.Errorf(ctx, "ERROR index retrieveMemc: %s", err)
// expired cookie may exist on client
http.Redirect(res, req, "/logout", http.StatusSeeOther)
return
}
tpl.ExecuteTemplate(res, "index.html", m)
}
示例6: deleteReplyHandler
// URL: /reply/{replyId}/delete
// 删除回复,只有管理员可以删除
func deleteReplyHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
replyId := vars["replyId"]
user, ok := currentUser(r)
if !ok {
http.Redirect(w, r, "/signin", http.StatusFound)
return
}
if !user.IsSuperuser {
message(w, r, "没用该权限", "对不起,你没有权限删除该回复", "error")
return
}
c := db.C("replies")
var reply Reply
err := c.Find(bson.M{"_id": bson.ObjectIdHex(replyId)}).One(&reply)
if err != nil {
message(w, r, "该回复不存在", "不存在该回复", "error")
return
}
err = c.Remove(bson.M{"_id": bson.ObjectIdHex(replyId)})
if err != nil {
message(w, r, "该回复不存在", "不存在该回复", "error")
return
}
c = db.C("topics")
// 减少该主题的回复数量
c.Update(bson.M{"_id": reply.TopicId}, bson.M{"$inc": bson.M{"replycount": -1}})
var topic Topic
c.Find(bson.M{"_id": reply.TopicId}).One(&topic)
if topic.LatestReplyId == replyId {
if topic.ReplyCount == 0 {
// 如果删除后没有回复,设置最后回复id为空,最后回复时间为创建时间
c.Update(bson.M{"_id": topic.Id_}, bson.M{"$set": bson.M{"latestreplyid": "", "latestrepliedat": reply.CreatedAt}})
} else {
// 如果删除的是该主题最后一个回复,设置主题的最新回复id,和时间
var latestReply Reply
c = db.C("replies")
c.Find(bson.M{"topicid": topic.Id_}).Sort("-createdat").Limit(1).One(&latestReply)
c = db.C("topics")
c.Update(bson.M{"_id": topic.Id_}, bson.M{"$set": bson.M{"latestreplyid": latestReply.Id_.Hex(), "latestrepliedat": latestReply.CreatedAt}})
}
}
c = db.C("status")
var status Status
c.Find(nil).One(&status)
c.Update(bson.M{"_id": status.Id_}, bson.M{"$inc": bson.M{"replycount": -1}})
http.Redirect(w, r, "/t/"+reply.TopicId.Hex(), http.StatusFound)
}
示例7: handleContacts
func handleContacts(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Redirect(w, r, "/?error=noDirectAccess", http.StatusTemporaryRedirect)
return
}
url, err := getProperDomainNameFromUrl(r.FormValue("url"))
if err != nil {
http.Redirect(w, r, "/?error=badUrl", http.StatusTemporaryRedirect)
return
}
if !isUrlOnGoogleApp(w, r, url) {
http.Redirect(w, r, "/?error=notOnGoogleApps", http.StatusTemporaryRedirect)
return
}
ctx := appengine.NewContext(r)
config.RedirectURL = fmt.Sprintf(`http://%s/contacts/export`, r.Host)
x := AppState{url}
url = config.AuthCodeURL(x.encodeState())
ctx.Infof("Auth: %v", url)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
示例8: adminLoginPostHandler
func (n *node) adminLoginPostHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "cannot parse form", 422)
return
}
usr := r.Form.Get("user")
pass := r.Form.Get("pass")
if usr == n.u.conf.AdminUser && pass == n.u.conf.AdminPass {
s, err := n.sc.Start(w, r)
if err != nil {
// TODO
fmt.Println(err)
}
defer s.Flush()
s.Set("user", usr)
s.Set("test", time.Now().Unix())
p, ok := s.Get("prevReq").(string)
if ok && p != "" {
http.Redirect(w, r, p, 302)
return
}
http.Redirect(w, r, "/"+n.u.conf.AdminPathPrefix, 303)
return
}
http.Error(w, "unauthorized", 401)
}
示例9: submitPage
// submitPage is the submission page served on "/submit/"
func submitPage(w http.ResponseWriter, r *http.Request, t *template.Template) {
if r.Method == "POST" {
if r.FormValue("title") == "" || r.FormValue("content") == "" {
http.Redirect(w, r, "/submit/", http.StatusFound)
return
}
newEntry := &blog.BlogEntry{
Title: r.FormValue("title"),
Content: r.FormValue("content"),
Date: time.Now(),
}
blogState.AddEntry(newEntry)
sort.Sort(blog.ByDate{blogState.Entries})
http.Redirect(w, r, "/", http.StatusFound)
} else {
err := t.Execute(w, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
示例10: adminWrap
func adminWrap(h AdminHandlerFunc) func(http.ResponseWriter, *http.Request, *Session) {
return func(w http.ResponseWriter, r *http.Request, session *Session) {
if !session.IsLoggedIn() {
http.Redirect(w, r, "/login", 303)
return
}
// revert login as another user
if session.OriginalId != 0 {
session.UserId = session.OriginalId
session.OriginalId = 0
}
// confirm session admin and also user still admin
user := UserDetails(session.UserId)
if !user.Admin || !session.Admin {
http.Redirect(w, r, "/panel/dashboard", 303)
return
}
var frameParams FrameParams
if r.URL.Query()["message"] != nil {
frameParams.Message.Text = r.URL.Query()["message"][0]
if r.URL.Query()["type"] != nil {
frameParams.Message.Type = r.URL.Query()["type"][0]
} else {
frameParams.Message.Type = "info"
}
}
h(w, r, session, frameParams)
}
}
示例11: LoginHandler
// Handles user login. If user is logged in, redirects to '/'.
func LoginHandler(w http.ResponseWriter, r *http.Request) {
if auth.LoggedIn(w, r, s) {
http.Redirect(w, r, "/auth-check", 302)
return
}
if r.Method == "GET" {
t, err := template.ParseFiles("views/login.html")
if err != nil {
log.Println(err)
return
}
t.Execute(w, nil)
} else {
// Get values from html form
user := r.FormValue("user")
pass := r.FormValue("password")
// Attempt to validate user, if incorrect info, send user back to login page
if auth.ValidateLogin(user, pass, db) {
cookie, err := createCookie()
if err != nil {
log.Println(err)
http.Redirect(w, r, "/login", 302)
return
}
http.SetCookie(w, cookie)
http.Redirect(w, r, "/auth-check", 302)
} else {
http.Redirect(w, r, "/login", 302)
}
}
}
示例12: Permissions
func Permissions(permissionName string) martini.Handler {
return func(token oauth2.Tokens, w http.ResponseWriter, r *http.Request, c martini.Context) {
if token == nil || token.Expired() {
next := url.QueryEscape(r.URL.RequestURI())
http.Redirect(w, r, oauth2.PathLogin+"?next="+next, 302)
return
}
id, err := GetId(token.Access())
if err != nil {
log.Printf("Error getting player token id:", err.Error())
http.Redirect(w, r, "/error", 302)
return
}
user := ols.GetUserDAO().GetUserFB(id)
if user.LeagueId == 0 {
next := url.QueryEscape(r.URL.RequestURI())
http.Redirect(w, r, "/register?next="+next, 302)
}
// TODO - fix this
if !true {
http.Redirect(w, r, "/error", 302)
}
c.Map(user)
c.Next()
}
}
示例13: Upload
func (c *Controller) Upload() {
fmt.Println("upload")
err := c.R.ParseForm()
if err != nil {
fmt.Println("error parse form", err)
http.Redirect(c.W, c.R, "/", http.StatusFound)
return
}
file, header, err := c.R.FormFile("file")
if err != nil {
fmt.Println("error get file from request", err)
http.Redirect(c.W, c.R, "/", http.StatusFound)
return
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
data := strings.Join(lines, "\n")
err = c.U.SaveFile([]byte(data), header.Filename)
if err != nil {
fmt.Println("error save file", err)
http.Redirect(c.W, c.R, "/", http.StatusFound)
return
}
http.Redirect(c.W, c.R, "/open/"+header.Filename, http.StatusFound)
}
示例14: 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)
}
示例15: ServeHTTP
func (b *BouncerHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
reqParams := BouncerParamsFromValues(req.URL.Query())
if reqParams.Product == "" {
http.Redirect(w, req, "http://www.mozilla.org/", 302)
return
}
if reqParams.OS == "" {
reqParams.OS = DefaultOS
}
if reqParams.Lang == "" {
reqParams.Lang = DefaultLang
}
isWinXpClient := isWindowsXPUserAgent(req.UserAgent())
// If the client is not WinXP and attribution_code is set, redirect to the stub service
if b.StubRootURL != "" &&
reqParams.AttributionCode != "" &&
reqParams.AttributionSig != "" &&
!isWinXpClient {
stubURL := b.stubAttributionURL(reqParams)
http.Redirect(w, req, stubURL, 302)
return
}
// HACKS
// If the user is coming from windows xp or vista, send a sha1
// signed product
// HACKS
if reqParams.OS == "win" && isWinXpClient {
reqParams.Product = sha1Product(reqParams.Product)
}
url, err := b.URL(reqParams.Lang, reqParams.OS, reqParams.Product)
if err != nil {
http.Error(w, "Internal Server Error.", http.StatusInternalServerError)
log.Println(err)
return
}
if url == "" {
http.NotFound(w, req)
return
}
if b.CacheTime > 0 {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", b.CacheTime/time.Second))
}
// If ?print=yes, print the resulting URL instead of 302ing
if reqParams.PrintOnly {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(url))
return
}
http.Redirect(w, req, url, 302)
}