login.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "html/template"
  6. "io"
  7. "net/http"
  8. "path/filepath"
  9. "cnphper.com/model"
  10. )
  11. type LoginRet struct {
  12. Errno int `json:"errno"`
  13. Error string `json:"error"`
  14. Data Session `json:"data"`
  15. }
  16. func login_index(resp http.ResponseWriter, req *http.Request) {
  17. if req.Method == "GET" {
  18. //视图输出
  19. tmpl, err := template.ParseFiles(filepath.Join(Cfg.TmplDir, "login.tmpl"))
  20. if err != nil {
  21. io.WriteString(resp, fmt.Sprintf("Error: %s\n", err.Error()))
  22. } else {
  23. tmpl.Execute(resp, req)
  24. }
  25. } else if req.Method == "POST" {
  26. req.ParseForm()
  27. account := req.PostForm.Get("account")
  28. passwd := req.PostForm.Get("passwd")
  29. if account == "" {
  30. json, _ := json.Marshal(ErrorRet{Errno: 1, Error: "用户名不能为空!"})
  31. resp.Write(json)
  32. } else if passwd == "" {
  33. json, _ := json.Marshal(ErrorRet{Errno: 2, Error: "密码不能为空!"})
  34. resp.Write(json)
  35. } else {
  36. mdlAccounts := model.NewAccounts(Db)
  37. row, err := mdlAccounts.Login(account, passwd)
  38. if err != nil {
  39. json, _ := json.Marshal(ErrorRet{Errno: 3, Error: err.Error()})
  40. resp.Write(json)
  41. } else {
  42. sessid := makeSessionId(req.RemoteAddr)
  43. sess := Session{
  44. Sess: sessid,
  45. Account: row,
  46. }
  47. SessPoll.Set(sessid, &sess)
  48. cookie := &http.Cookie{
  49. Name: "sessid",
  50. Value: sessid,
  51. Path: "/",
  52. }
  53. resp.Header().Add("Set-Cookie", cookie.String())
  54. json, _ := json.Marshal(LoginRet{Errno: 0, Error: "", Data: sess})
  55. resp.Write(json)
  56. }
  57. }
  58. }
  59. }