main.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package main
  2. import (
  3. "log"
  4. "os"
  5. "time"
  6. "fmt"
  7. "net/http"
  8. "html/template"
  9. "github.com/gorilla/mux"
  10. "github.com/gorilla/sessions"
  11. )
  12. type Page struct {
  13. Title string
  14. Body []byte
  15. }
  16. var (
  17. logger *log.Logger
  18. dBConnector connection
  19. sessionsStore = sessions.NewCookieStore([]byte("mysecretcookie"))
  20. indexTemplate = template.Must(template.ParseFiles("ui\\templates\\index.html"))
  21. logInTemplate = template.Must(template.ParseFiles("ui\\templates\\login.html"))
  22. signInTemplate = template.Must(template.ParseFiles("ui\\templates\\signin.html"))
  23. gameTemplate = template.Must(template.ParseFiles("ui\\templates\\game.html"))
  24. )
  25. func indexHandler(w http.ResponseWriter, r *http.Request) {
  26. data := struct {
  27. User string
  28. Title string
  29. Items []string
  30. }{
  31. User: "",
  32. Title: "My page",
  33. Items: []string{
  34. "My photos",
  35. "My blog",
  36. "More",
  37. },
  38. }
  39. session, _ := sessionsStore.Get(r, "session")
  40. var (
  41. password string
  42. ok3 bool
  43. )
  44. untyped, ok := session.Values["username"]
  45. if ok {
  46. username, ok1 := untyped.(string)
  47. if ok1 {
  48. data.User = username
  49. untyped, ok2 := session.Values["password"]
  50. if ok2 {
  51. password, ok3 = untyped.(string)
  52. }
  53. }
  54. }
  55. indexTemplate.Execute(w, data)
  56. if ok3 {
  57. w.Write([]byte(password))
  58. }
  59. }
  60. func indexPostHandler(w http.ResponseWriter, r *http.Request) {
  61. fmt.Print("POST")
  62. }
  63. func logInGetHandler(w http.ResponseWriter, r *http.Request) {
  64. data := struct {
  65. Username string
  66. Password string
  67. Error string
  68. }{
  69. Username: "",
  70. Password: "",
  71. Error: "",
  72. }
  73. logInTemplate.Execute(w, data)
  74. }
  75. func logInPostHandler(w http.ResponseWriter, r *http.Request) {
  76. r.ParseForm()
  77. username := r.PostForm.Get("username")
  78. password := r.PostForm.Get("password")
  79. if (dBConnector.LogIn(username, password)){
  80. session, _ := sessionsStore.Get(r, "session")
  81. session.Values["username"] = username
  82. session.Values["password"] = password
  83. session.Save(r,w)
  84. fmt.Printf("%s\n%s\n",username,password)
  85. http.Redirect(w, r, "/", http.StatusFound)
  86. } else {
  87. data := struct {
  88. Username string
  89. Password string
  90. Error string
  91. }{
  92. Username: username,
  93. Password: password,
  94. Error: "Неверный логин либо пароль",
  95. }
  96. fmt.Printf("Login error")
  97. logInTemplate.Execute(w, data)
  98. //w.Write([]byte("Login error"))
  99. }
  100. }
  101. func logOutGetHandler(w http.ResponseWriter, r *http.Request) {
  102. session, _ := sessionsStore.Get(r, "session")
  103. session.Options.MaxAge = -1
  104. session.Save(r, w)
  105. untyped, ok := session.Values["username"]
  106. if ok {
  107. username, ok1 := untyped.(string)
  108. if ok1 {
  109. logger.Printf("User %s loged out", username)
  110. }
  111. }
  112. http.Redirect(w, r, "/", http.StatusFound)
  113. }
  114. func signInGetHandler(w http.ResponseWriter, r *http.Request) {
  115. signInTemplate.Execute(w, nil)
  116. }
  117. func signInPostHandler(w http.ResponseWriter, r *http.Request) {
  118. r.ParseForm()
  119. username := r.PostForm.Get("username")
  120. password := r.PostForm.Get("password")
  121. passwordRepeat := r.PostForm.Get("password-repeat")
  122. data := struct {
  123. Username string
  124. Password string
  125. PasswordRepeat string
  126. Error string
  127. }{
  128. Username: username,
  129. Password: password,
  130. PasswordRepeat: passwordRepeat,
  131. Error: "",
  132. }
  133. if dBConnector.IsNameUsed(username) {
  134. data.Error = "Имя пользователя занято"
  135. } else {
  136. if (password != passwordRepeat) {
  137. data.Error = "Введенные пароли не совпадают"
  138. } else {
  139. if dBConnector.SigInUser(username,password) {
  140. session, _ := sessionsStore.Get(r, "session")
  141. session.Values["username"] = username
  142. session.Values["password"] = password
  143. session.Save(r,w)
  144. http.Redirect(w, r, "/", http.StatusFound)
  145. } else {
  146. data.Error = "Произошла внутреняя ошибка при регистрации нового пользователя"
  147. }
  148. }
  149. }
  150. signInTemplate.Execute(w, data)
  151. }
  152. func gameGetHandler(w http.ResponseWriter, r *http.Request) {
  153. gameTemplate.Execute(w, nil)
  154. }
  155. func gamePostHandler(w http.ResponseWriter, r *http.Request){ //TODO запись score в таблицу
  156. if err := r.ParseForm(); err != nil {
  157. fmt.Fprintf(w, "ParseForm() err: %v", err)
  158. return
  159. }
  160. fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
  161. score := r.FormValue("score")
  162. fmt.Fprintf(w,"score = %s\n", score)
  163. fmt.Printf("score = %s\n", score)
  164. }
  165. func createLogger() {
  166. startTime := time.Now()
  167. logFileName := "logs/go-site_log_" + startTime.Format("2006-01-02_15-04-05") + ".txt"
  168. file, err := os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
  169. logger = log.New(file, "logger: ", log.Lshortfile)
  170. if err != nil {
  171. log.Fatal(err)
  172. }
  173. }
  174. type user struct{
  175. idusers int
  176. username string
  177. password string
  178. }
  179. func main() {
  180. createLogger()
  181. logger.Print("Hello, log file!")
  182. requestRouter := mux.NewRouter()
  183. dBConnector.Init("config.json")
  184. requestRouter.HandleFunc("/", indexHandler).Methods("GET")
  185. //requestRouter.HandleFunc("/", indexPostHandler).Methods("POST") //Есть ли нужда в обработке POST для /
  186. requestRouter.HandleFunc("/login/", logInGetHandler).Methods("GET")
  187. requestRouter.HandleFunc("/login/", logInPostHandler).Methods("POST")
  188. requestRouter.HandleFunc("/logout/", logOutGetHandler).Methods("GET")
  189. requestRouter.HandleFunc("/signin/", signInGetHandler).Methods("GET")
  190. requestRouter.HandleFunc("/signin/", signInPostHandler).Methods("POST")
  191. requestRouter.HandleFunc("/game/", gameGetHandler).Methods("GET")
  192. requestRouter.HandleFunc("/", gamePostHandler).Methods("POST")
  193. http.Handle("/", requestRouter)
  194. logger.Fatal(http.ListenAndServe(":8080", nil))
  195. }