-3

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"
}
Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
A.H
  • 129
  • 2
  • 10
  • 3
    On what line do you get the runtime error mentioned in the title? – ANisus Nov 01 '14 at 10:07
  • hi, when i running in the browser http://localhost:8080/login. in the command prompt am getting error invalid memoru address or nil pointer dereference. – A.H Nov 01 '14 at 10:11
  • 1
    @Harish: you need to show the stack trace or at least tell us where the nil pointer dereference happened – JimB Nov 01 '14 at 10:47
  • in Command prompt i am getting error which i cant read..2014/11/01 16:38:48 http: panic serving [::1]:53092: runtime error: invalid memo ry address or nil pointer dereference goroutine 49 [running]: net/http.func·011() c:/go/src/pkg/net/http/server.go:1100 +0xbe runtime.panic(0x868860, 0xb60842) c:/go/src/pkg/runtime/panic.c:248 +0x1d3 github.com/astaxie/beego/session.(*Manager).SessionStart(0x0, 0x151e78, 0xc08212 0000, 0xc082021ad0, 0x0, 0x0) D:/go_programs/src/github.com/astaxie/beego/session/session.go:148 +0x54 main.login(0x151e78, 0xc082120000, 0xc082021ad0) – A.H Nov 01 '14 at 11:10
  • 2
    @Harris: That is not helpful. If you provide a **minimal** complete example and a complete stacktrace you might be helped. Please format bot (code and stacktrace) properly. Most probably you just didn't initialize a pointer. – Volker Nov 01 '14 at 11:52
  • 2
    @Harish: To create an example for your question, follow these instructions: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – peterSO Nov 01 '14 at 13:21

2 Answers2

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.

gliptak
  • 3,592
  • 2
  • 29
  • 61
dyoo
  • 11,795
  • 1
  • 34
  • 44
-1

As this is the one line you used in code :

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

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.

shyam
  • 596
  • 9
  • 18
  • **Never** use a line such as that in any code. **Never** ignore errors. In the specific case of templates you can do `t := template.Must(template.ParseFiles("login.tpl"))` if you insist on not otherwise handling the error. – Dave C Jun 12 '15 at 16:03
  • @DaveC You can see [here](http://astaxie.gitbooks.io/build-web-application-with-golang/content/en/04.1.html) . The line of code I mentioned can be used and the user, who asked the question, also used that. The thing I was saying is that `reference for the files must be correct otherwise that can cause errors` like above. And yes this was the problem I faced initially, because the `.tpl` file was not in the same folder as the `.go` file and that caused the error for unknown reference of that `index.tpl` file. – shyam Jun 13 '15 at 08:55
  • 1
    "can be used", yes and you "can" do "rm -rf /" as well if you want to shoot yourself in the foot. Throwing away the error when parsing a template is completely wrong. Arranging in a specific case to have it not blow up on you does not make it right. – Dave C Jun 13 '15 at 11:54
  • I am not saying you to use that in the code. The thing I am trying to explain is, that the reference for the external files must be correct. I get this error because there was no such file named `index.tpl` at that reference. So the thing I'm trying to say is, I faced this type of error and corrected by creating a file named `index.tpl`. – shyam Jun 14 '15 at 18:08