package main import ( "encoding/json" "fmt" "html/template" "io" "net/http" "path/filepath" "cnphper.com/model" ) type LoginRet struct { Errno int `json:"errno"` Error string `json:"error"` Data Session `json:"data"` } func login_index(resp http.ResponseWriter, req *http.Request) { if req.Method == "GET" { //视图输出 tmpl, err := template.ParseFiles(filepath.Join(Cfg.TmplDir, "login.tmpl")) if err != nil { io.WriteString(resp, fmt.Sprintf("Error: %s\n", err.Error())) } else { tmpl.Execute(resp, req) } } else if req.Method == "POST" { req.ParseForm() account := req.PostForm.Get("account") passwd := req.PostForm.Get("passwd") if account == "" { json, _ := json.Marshal(ErrorRet{Errno: 1, Error: "用户名不能为空!"}) resp.Write(json) } else if passwd == "" { json, _ := json.Marshal(ErrorRet{Errno: 2, Error: "密码不能为空!"}) resp.Write(json) } else { mdlAccounts := model.NewAccounts(Db) row, err := mdlAccounts.Login(account, passwd) if err != nil { json, _ := json.Marshal(ErrorRet{Errno: 3, Error: err.Error()}) resp.Write(json) } else { sessid := makeSessionId(req.RemoteAddr) sess := Session{ Sess: sessid, Account: row, } SessPoll.Set(sessid, &sess) cookie := &http.Cookie{ Name: "sessid", Value: sessid, Path: "/", } resp.Header().Add("Set-Cookie", cookie.String()) json, _ := json.Marshal(LoginRet{Errno: 0, Error: "", Data: sess}) resp.Write(json) } } } }