http_login.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "html/template"
  6. "io"
  7. "net/http"
  8. "path/filepath"
  9. "redisdog/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. resp.Write(ERROR_RET(1, "用户名不能为空!"))
  31. } else if passwd == "" {
  32. resp.Write(ERROR_RET(2, "密码不能为空!"))
  33. } else {
  34. mdlAccounts := model.NewAccounts(Db)
  35. row, err := mdlAccounts.Login(account, passwd)
  36. if err != nil {
  37. resp.Write(ERROR_RET(3, err.Error()))
  38. } else {
  39. sessid := makeSessionId(req.RemoteAddr)
  40. sess := Session{
  41. Sess: sessid,
  42. Account: row,
  43. }
  44. SessPoll.Set(sessid, &sess)
  45. cookie := &http.Cookie{
  46. Name: "sessid",
  47. Value: sessid,
  48. Path: "/",
  49. }
  50. resp.Header().Add("Set-Cookie", cookie.String())
  51. ret, _ := json.Marshal(LoginRet{Errno: 0, Error: "", Data: sess})
  52. resp.Write(ret)
  53. }
  54. }
  55. }
  56. }