123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244 |
- package main
- import (
- "log"
-
- "os"
- "time"
- "fmt"
- "net/http"
- "html/template"
- "github.com/gorilla/mux"
- "github.com/gorilla/sessions"
- )
- type Page struct {
- Title string
- Body []byte
- }
- var (
- logger *log.Logger
- dBConnector connection
- sessionsStore = sessions.NewCookieStore([]byte("mysecretcookie"))
- indexTemplate = template.Must(template.ParseFiles("ui\\templates\\index.html"))
- logInTemplate = template.Must(template.ParseFiles("ui\\templates\\login.html"))
- signInTemplate = template.Must(template.ParseFiles("ui\\templates\\signin.html"))
- gameTemplate = template.Must(template.ParseFiles("ui\\templates\\game.html"))
- )
- func indexHandler(w http.ResponseWriter, r *http.Request) {
- data := struct {
- User string
- Title string
- Items []string
- }{
- User: "",
- Title: "My page",
- Items: []string{
- "My photos",
- "My blog",
- "More",
- },
- }
-
- session, _ := sessionsStore.Get(r, "session")
- var (
- password string
- ok3 bool
- )
- untyped, ok := session.Values["username"]
- if ok {
- username, ok1 := untyped.(string)
- if ok1 {
- data.User = username
- untyped, ok2 := session.Values["password"]
- if ok2 {
- password, ok3 = untyped.(string)
-
- }
- }
- }
-
- indexTemplate.Execute(w, data)
- if ok3 {
- w.Write([]byte(password))
- }
- }
- func indexPostHandler(w http.ResponseWriter, r *http.Request) {
- fmt.Print("POST")
- }
- func logInGetHandler(w http.ResponseWriter, r *http.Request) {
- data := struct {
- Username string
- Password string
- Error string
- }{
- Username: "",
- Password: "",
- Error: "",
- }
- logInTemplate.Execute(w, data)
- }
- func logInPostHandler(w http.ResponseWriter, r *http.Request) {
- r.ParseForm()
- username := r.PostForm.Get("username")
- password := r.PostForm.Get("password")
- if (dBConnector.LogIn(username, password)){
- session, _ := sessionsStore.Get(r, "session")
- session.Values["username"] = username
- session.Values["password"] = password
- session.Save(r,w)
- fmt.Printf("%s\n%s\n",username,password)
- http.Redirect(w, r, "/", http.StatusFound)
- } else {
- data := struct {
- Username string
- Password string
- Error string
- }{
- Username: username,
- Password: password,
- Error: "Неверный логин либо пароль",
- }
- fmt.Printf("Login error")
- logInTemplate.Execute(w, data)
- //w.Write([]byte("Login error"))
- }
- }
- func logOutGetHandler(w http.ResponseWriter, r *http.Request) {
- session, _ := sessionsStore.Get(r, "session")
- session.Options.MaxAge = -1
- session.Save(r, w)
-
- untyped, ok := session.Values["username"]
- if ok {
- username, ok1 := untyped.(string)
- if ok1 {
- logger.Printf("User %s loged out", username)
- }
- }
- http.Redirect(w, r, "/", http.StatusFound)
- }
- func signInGetHandler(w http.ResponseWriter, r *http.Request) {
- signInTemplate.Execute(w, nil)
- }
- func signInPostHandler(w http.ResponseWriter, r *http.Request) {
- r.ParseForm()
- username := r.PostForm.Get("username")
- password := r.PostForm.Get("password")
- passwordRepeat := r.PostForm.Get("password-repeat")
- data := struct {
- Username string
- Password string
- PasswordRepeat string
- Error string
- }{
- Username: username,
- Password: password,
- PasswordRepeat: passwordRepeat,
- Error: "",
- }
- if dBConnector.IsNameUsed(username) {
- data.Error = "Имя пользователя занято"
- } else {
- if (password != passwordRepeat) {
- data.Error = "Введенные пароли не совпадают"
- } else {
- if dBConnector.SigInUser(username,password) {
-
- session, _ := sessionsStore.Get(r, "session")
- session.Values["username"] = username
- session.Values["password"] = password
- session.Save(r,w)
- http.Redirect(w, r, "/", http.StatusFound)
- } else {
- data.Error = "Произошла внутреняя ошибка при регистрации нового пользователя"
- }
- }
- }
- signInTemplate.Execute(w, data)
- }
- func gameGetHandler(w http.ResponseWriter, r *http.Request) {
- gameTemplate.Execute(w, nil)
- }
- func gamePostHandler(w http.ResponseWriter, r *http.Request){ //TODO запись score в таблицу
- if err := r.ParseForm(); err != nil {
- fmt.Fprintf(w, "ParseForm() err: %v", err)
- return
- }
- fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
- score := r.FormValue("score")
- fmt.Fprintf(w,"score = %s\n", score)
- fmt.Printf("score = %s\n", score)
- }
- func createLogger() {
- startTime := time.Now()
- logFileName := "logs/go-site_log_" + startTime.Format("2006-01-02_15-04-05") + ".txt"
- file, err := os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
- logger = log.New(file, "logger: ", log.Lshortfile)
-
- if err != nil {
- log.Fatal(err)
- }
- }
- type user struct{
- idusers int
- username string
- password string
- }
- func main() {
-
-
- createLogger()
- logger.Print("Hello, log file!")
- requestRouter := mux.NewRouter()
-
- dBConnector.Init("config.json")
-
- requestRouter.HandleFunc("/", indexHandler).Methods("GET")
- //requestRouter.HandleFunc("/", indexPostHandler).Methods("POST") //Есть ли нужда в обработке POST для /
- requestRouter.HandleFunc("/login/", logInGetHandler).Methods("GET")
- requestRouter.HandleFunc("/login/", logInPostHandler).Methods("POST")
- requestRouter.HandleFunc("/logout/", logOutGetHandler).Methods("GET")
- requestRouter.HandleFunc("/signin/", signInGetHandler).Methods("GET")
- requestRouter.HandleFunc("/signin/", signInPostHandler).Methods("POST")
- requestRouter.HandleFunc("/game/", gameGetHandler).Methods("GET")
- requestRouter.HandleFunc("/", gamePostHandler).Methods("POST")
- http.Handle("/", requestRouter)
- logger.Fatal(http.ListenAndServe(":8080", nil))
- }
|