运行时错误:无效的内存地址或空指针解引用 – golang

huangapple go评论76阅读模式
英文:

runtime error:Invalid memory Address or nil pointer dereference-golang

问题

我是新手,正在尝试使用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()  // 解析参数,默认是不会解析的
    fmt.Println("the information of form is", r.Form)  // 输出到服务器端
    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!") // 这个写入到 w 的是输出到客户端的
}

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
    Get(key interface{}) interface{}
    Delete(key interface{}) error
    SessionID() string
}

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 {
        // 登录的逻辑判断
        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)
    if err != nil {
        log.Fatal("ListenAndServe: ", 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"
}

希望对你有帮助!

英文:

I am new to golang, am trying develop a login page with sesions. the code is building successfully but when I run in browser its saying 404 page not found.can any one help for me. Thanks in advance.
Here is my code

// 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"
}

答案1

得分: 3

你在不同作用域中有两个变量,都叫做globalSessions。一个是在main.go中的定义,它在全局作用域中定义;另一个是在main函数中定义的,它是main函数的局部变量。这是两个不同的变量。你的代码犯了这个混淆它们的错误。

你可以通过仔细观察堆栈跟踪条目来看到这一点:

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

这指向globalSessions未初始化的问题,因为它是nil。之后,故障排除就是直接查看程序,看看哪里涉及到了globalSessions

请注意,你应该将堆栈跟踪作为问题的一部分包含在内。不要只将其作为注释添加。包含这些信息非常重要:否则,我们将无法轻松地追踪问题。请提高问题的质量,以便人们更容易帮助你。

此外,你可能需要认真查看go vet,它是一个帮助捕捉此类问题的工具。

英文:

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.

答案2

得分: -1

由于这是你在代码中使用的一行代码:

<!-- begin snippet: js hide: false -->

<!-- language: go -->

t, _ := template.ParseFiles(&quot;login.tpl&quot;)

<!-- end snippet -->

所以你需要检查的是文件 login.tpl 是否位于正确的位置,是否在应该的位置。如果不是,则需要“更正其引用”,并对其他引用进行相同的检查。

这对我很有帮助。

英文:

As this is the one line you used in code :

<!-- begin snippet: js hide: false -->

<!-- language: go -->

t, _ := template.ParseFiles(&quot;login.tpl&quot;)

<!-- end snippet -->

So what you need to check is whether the file login.tpl is at the correct location, where it must be, or not. If not then correct the reference of it and also check same for the other references.

This helped me.

huangapple
  • 本文由 发表于 2014年11月1日 16:29:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/26687472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定