英文:
Is the Go Appengine tutorial missing LoginURL redirect statements?
问题
当我运行演示代码时,我没有被重定向到Google账号登录界面。
教程中提到:“请注意,如果用户未登录,则HTTP状态码302 Found会将浏览器重定向到Google账号登录界面。”
代码中似乎缺少一些内容,例如:
if u == nil {
    url, _ := user.LoginURL(ctx, "/")
    fmt.Fprintf(w, `<a href="%s">Sign in or register</a>`, url)
    return
}
如果我理解有误,请问当前的代码是如何将用户重定向到登录界面的?
英文:
I'm not getting redirected to the Google account sign-in screen when I run the demo code.
https://cloud.google.com/appengine/docs/standard/go/getting-started/authenticating-users
The tutorial mentions: "Note that if the user is not signed in, an HTTP status code of 302 Found redirects the browser to the Google account sign-in screen."
   func sign(w http.ResponseWriter, r *http.Request) {  
        // [START new_context]  
        c := appengine.NewContext(r)  
        // [END new_context]         
        g := Greeting{  
                Content: r.FormValue("content"),  
                Date:    time.Now(),  
        }  
        // [START if_user]  
        if u := user.Current(c); u != nil {  
                g.Author = u.String()  
        }  
        key := datastore.NewIncompleteKey(c, "Greeting", guestbookKey(c))  
        _, err := datastore.Put(c, key, &g)  
        if err != nil {  
                http.Error(w, err.Error(), http.StatusInternalServerError)  
                return  
        }
        http.Redirect(w, r, "/", http.StatusFound)
        // [END if_user]    
   }
Source code:
https://github.com/GoogleCloudPlatform/appengine-guestbook-go/blob/part4-usingdatastore/hello.go
It seems something is missing e.g.:
if u == nil {
                url, _ := user.LoginURL(ctx, "/")
                fmt.Fprintf(w, `<a href="%s">Sign in or register</a>`, url)
                return
        } 
If I'm wrong, how does the current code redirect user to the sign-in screen?
答案1
得分: 1
你是正确的。要登录用户,你需要将他们重定向到上面的LoginURL。一旦用户访问此URL,应用引擎将允许他们使用他们的Google账号登录。
然而,你上面提供的示例代码并不要求用户登录。如果用户已登录,代码会获取他们的ID,并将其用作问候语的作者。如果没有登录,代码会将用户标记为匿名,如下模板所示:
{{with .Author}}
  <p><b>{{.}}</b> 写道:</p>
{{else}}
  <p>一个匿名人写道:</p>
{{end}}
英文:
You are correct. To log in a user, you'll have to redirect them to a LoginURL as above. Once a user accesses this URL, app engine will let them log in using their google account.
However, the example code you've linked above does not require a user to be logged in. If a user is logged in, the code gets their ID and uses that as the greeting's author. If not, it just calls the user anonymous, as per the template:
{{with .Author}}
  <p><b>{{.}}</b> wrote:</p>
{{else}
  <p>An anonymous person wrote:</p>
{{end}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论