关于session,求帮忙找找错

ggsimida · 2016-03-07 13:24:10 · 3391 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2016-03-07 13:24:10 的主题,其中的信息可能已经有所发展或是发生改变。

登陆时进入loginin,密码正确后创建session,返回true。网页端拿到true后跳转到第二张页面,验证session,此时从firebug上就看不到请求,拿到的session也为空,很奇怪,不知道哪里错了。想请大家帮忙看看 func sessionCreate(w http.ResponseWriter, r *http.Request, username string) { //创建session state := string(random.NewRandomEx()) //生成服务器端随机数 fmt.Println("state:", state)

sidBytes, err := id.NewSessionId() //生成客户端随机数
if err != nil {
    io.WriteString(w, err.Error())
    fmt.Println(err)
    return
}
sid := string(sidBytes)
fmt.Println("sid:", sid)

if err := sessionStorage.Add(sid, state); err != nil { //将两个随机数对应
    io.WriteString(w, err.Error())
    fmt.Println(err)
    return
}

cookie := http.Cookie{ //生成cookie
    Name:  "sid",
    Value: sid,
}
http.SetCookie(w, &cookie) //将cookie发送给页面

cookie = http.Cookie{
    Name:  "username",
    Value: username,
}
http.SetCookie(w, &cookie)

}

func verifySession(w http.ResponseWriter, r *http.Request) bool { //验证session fmt.Println("verifySession is running...")

cookie, err := r.Cookie("sid") //获取cookie的sid的值,一个sid对应一个值,若能获取到值,即正确
fmt.Println("cookie:", cookie)
if err != nil {
    fmt.Println(err)
    return false
}

_, err = sessionStorage.Get(cookie.Value)
if err != nil {
    fmt.Println(err)
    return false
}
return true

} func Sessiondelete(w http.ResponseWriter, r *http.Request) { //删除session

cookie, err := r.Cookie("sid") //获取cookie的sid的值,一个sid对应一个值,若能获取到值,即正确
if err != nil {
    fmt.Println(err)
    return
}

err = sessionStorage.Delete(cookie.Value)
if err != nil {
    fmt.Println(err)
    io.WriteString(w, `{"success": "false"}`)
    return
}
io.WriteString(w, `{"success": "true"}`)

}

func pageFilter(req restful.Request, resp restful.Response, chain *restful.FilterChain) { v := path.Join("", req.PathParameter("subpath")) //页面过滤 suffix := v[len(v)-4:] if suffix == "html" { path := req.PathParameter("subpath")

    path_list := strings.Split(path, "/") //根据“/”分割
    w := resp.ResponseWriter
    r := req.Request
    ok := operate_utils.StringInSlice("manage", path_list) //若存在,返回true。即判断是否是后台页面
    //因为后台页面都在manage文件夹中
    if ok == true { //若是后台页面
        ok = operate_utils.StringInSlice("login.html", path_list) //判断是否是登陆界面
        if ok == true {                                           //若是,继续执行
            chain.ProcessFilter(req, resp)
            return
        } else { //若不是,对比session
            ver_res := verifySession(w, r)
            if ver_res == true { //若session正确,继续执行
                chain.ProcessFilter(req, resp)
                return
            }
            http.Redirect(w, r, "login.html", http.StatusFound)
            return
        }
    } else { //若不是后台页面
        fmt.Printf("我不是后台页面")
        chain.ProcessFilter(req, resp) //继续执行
        return
    }
}
chain.ProcessFilter(req, resp)

} func dataFilter(req restful.Request, resp restful.Response, chain restful.FilterChain) { w := resp.ResponseWriter //数据过滤 r := req.Request ver_res := verifySession(w, r) if ver_res == true { chain.ProcessFilter(req, resp) } else { fmt.Println({"success": "false"}) io.WriteString(resp, {"success": "false"}) } } func loginin(req restful.Request, resp *restful.Response) { //登录 fmt.Println("loginin is running...")

username1, _ := req.PostParameter("username")
password1, _ := req.PostParameter("password")
s := "username:" + username1 + ",password:" + password1
fmt.Println(s)

p := time.Now().String() //获取时间
q := p[:10]              //取前十位,年、月、日
a := []string{"select id,username,password from login where username='", username1, "'"}
b := strings.Join(a, "")
stmt1, err := db.Prepare(b)
if err != nil {
    fmt.Println("Query Error", err)
    return
}
defer stmt1.Close()
row1, err := stmt1.Query()
if err != nil {
    fmt.Println("Query Error", err)
    return
}
defer row1.Close()

var id string
var username string
var password string

for row1.Next() {
    err := row1.Scan(&id, &username, &password)
    if err != nil {
        fmt.Println("Query Error", err)
        return
    }
}
if username1 == username && password1 == password {
    if username1 == "" || password1 == "" {
        fmt.Println(`{"success": "false","msg":"login fail!"}`)
        io.WriteString(resp, `{"success": "false","msg":"login fail!"}`)
    } else {
        w := resp.ResponseWriter
        r := req.Request
        sessionCreate(w, r, username)

        fmt.Println(`{"success": "true","msg":"login success!"}`)
        io.WriteString(resp, `{"success": "true","msg":"login success!"}`)

        stmt2, err := db.Prepare("update login set last_login_time=? where id=?")
        if err != nil {
            fmt.Println("Query Error", err)
            return
        }
        defer stmt2.Close()
        res2, err := stmt2.Exec(q, id)
        if err != nil {
            fmt.Println("Query Error", err)
            return
        }
        num2, err := res2.RowsAffected()
        if err != nil {
            fmt.Println("Query Error", err)
            return
        }
        fmt.Println(num2)
    }
} else {
    fmt.Println(`{"success": "false","msg":"login fail!"}`)
    io.WriteString(resp, `{"success": "false","msg":"login fail!"}`)
}

}


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3391 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传