-3

我是golang的新手,正在尝试开发一个带有会话的登录页面。代码构建成功,但是当我在浏览器中运行时,它说找不到 404 页面。任何人都可以帮助我。提前致谢。这是我的代码

// main.go
package main

import (
        _ "HarishSession/routers"
       "github.com/astaxie/beego"
      "fmt"
        "net/http"
         "html/template"
            "strings"
              "log"
              "github.com/astaxie/beego/session"
               "sync"


    )


 var globalSessions *session.Manager
 var provides = make(map[string]Provider)

 func sayhelloName(w http.ResponseWriter, r *http.Request) {
            r.ParseForm()  // parse arguments, you have to call this by yourself
            fmt.Println("the information of form is",r.Form)  // print form information in server side
            fmt.Println("path", r.URL.Path)
             fmt.Println("scheme", r.URL.Scheme)
               fmt.Println(r.Form["url_long"])
                for k, v := range r.Form {
                   fmt.Println("key:", k)
                       fmt.Println("val:", strings.Join(v, ""))
    }
                      fmt.Fprintf(w, "Hello astaxie!") // send data to client side
}



type Manager struct {
    cookieName  string     //private cookiename
    lock        sync.Mutex // protects session
    provider    Provider
    maxlifetime int64
}


type Provider interface {
    SessionInit(sid string) (Session, error)
    SessionRead(sid string) (Session, error)
    SessionDestroy(sid string) error
    SessionGC(maxLifeTime int64)
}
type Session interface {
    Set(key, value interface{}) error //set session value
    Get(key interface{}) interface{}  //get session value
    Delete(key interface{}) error     //delete session value
    SessionID() string                //back current sessionID
}



func NewManager(provideName, cookieName string, maxlifetime int64) (*Manager, error) {
    provider, ok := provides[provideName]
    if !ok {
        return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
    }
    return &Manager{provider: provider, cookieName: cookieName, maxlifetime: maxlifetime}, nil
}


func login(w http.ResponseWriter, r *http.Request) {

sess := globalSessions.SessionStart(w,r)
r.ParseForm()

fmt.Println("method:", r.Method)
if r.Method == "GET" {
t, _ := template.ParseFiles("login.tpl")
w.Header().Set("Content-Type", "text/html")
t.Execute(w,sess.Get("username"))
} else {
//logic part of log in
fmt.Println("username:",r.Form["username"])
fmt.Println("password:",r.Form["password"])
http.Redirect(w,r,"/",302)
}
}



func main() {
var globalSessions *session.Manager
 http.HandleFunc("/", sayhelloName)
 http.HandleFunc("/login", login)
    err := http.ListenAndServe(":8080", nil) // set listen port
    if err != nil {
        log.Fatal("ListenAndServe the error is: ", err)
    }
    fmt.Println("hello")
    beego.Run()


    fmt.Println(globalSessions)
}


//router.go
package routers

import (
    "HarishSession/controllers"
    "github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.MainController{})
    beego.Router("/login", &controllers.MainController{})
}


//default.go
package controllers

import (
    "github.com/astaxie/beego"
)

type MainController struct {
    beego.Controller
}

func (this *MainController) Get() {
    this.Data["Website"] = "beego.me"
    this.Data["Email"] = "astaxie@gmail.com"
    this.TplNames = "index.tpl"
    this.TplNames="login.tpl"
}
4

2 回答 2

3

You have two variables at different scopes, each called globalSessions. One is in your definition in main.go, which is defined at global scope, and another is defined in the main function, and is defined as a local variable to main. These are separate variables. Your code is making this mistake of conflating them.

You can see this by paying closer attention to the stack trace entry:

github.com/astaxie/beego/session.(*Manager).SessionStart(0x0, 0x151e78, 0xc08212 0000, 0xc082021ad0, 0x0, 0x0) 

as this points to globalSessions being uninitialized due to being nil. After that, troubleshooting is a direct matter of looking at the program to see what touches globalSessions.

Note that you should include the stack trace as part of your question. Don't just add it as a comment. It's critical to include this information: otherwise we would not have been able to easily trace the problem. Please improve the quality of your questions to make it easier for people to help you.

Also, you may want to take a serious look at go vet, which is a tool that helps to catch problems like this.

于 2014-11-01T23:21:25.060 回答
-1

因为这是您在代码中使用的一行:

t, _ := template.ParseFiles("login.tpl")

所以你需要检查的是文件login.tpl是否在正确的位置,它必须在哪里,或者不在。如果不是,那么correct the reference of it还要检查其他参考文献。

这对我有帮助。

于 2015-06-12T06:24:51.947 回答