This repository has been archived by the owner on Jan 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
82 lines (71 loc) · 1.97 KB
/
handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"bufio"
"database/sql"
"fmt"
"html/template"
"net/http"
"os"
"strings"
"time"
_ "github.com/go-sql-driver/mysql"
)
//Member contains a name that will be sent to the database
type Member struct {
Name, CheckinTime string
}
//var templates = template.Must(template.ParseFiles("tmpl/index.html", "tmpl/checkin.html", "tmpl/current.html"))
var db *sql.DB
//IndexHandler handles calls to the index of the Server
func IndexHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "/static/index.html")
}
//CurrentHandler handles calls to the currently checked-in user list
func CurrentHandler(w http.ResponseWriter, r *http.Request) {
rows, _ := db.Query("SELECT * FROM checkedin")
defer rows.Close()
var members []Member
for rows.Next() {
m := Member{}
rows.Scan(&m.Name, &m.CheckinTime)
members = append(members, m)
}
t, err := template.ParseFiles("/tmpl/current.html")
if err != nil {
panic(err)
}
t.Execute(w, members)
}
//CheckinHandler adds team members to the database
func CheckinHandler(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
now := time.Now().Format(time.Kitchen)
res, err := db.Exec("INSERT INTO checkedin VALUES(?,?)", name, now)
if err != nil {
panic(err)
}
ra, _ := res.RowsAffected()
fmt.Printf("Rows affected: %d", ra)
time.AfterFunc(30*time.Minute, func() {
db.Exec("DELETE FROM checkedin WHERE Name=?", name)
})
http.Redirect(w, r, "/", http.StatusFound)
}
//OpenDB opens up the database
func OpenDB() {
read := bufio.NewReader(os.Stdin)
fmt.Print("Database name: ")
database, _ := read.ReadString('\n')
database = strings.Trim(database, "\n")
fmt.Print("Username: ")
user, _ := read.ReadString('\n')
user = strings.Trim(user, "\n")
fmt.Print("Password: ")
password, _ := read.ReadString('\n')
password = strings.Trim(password, "\n")
var err error
db, err = sql.Open("mysql", user+":"+password+"@/"+database+"?allowCleartextPasswords=true")
if err != nil {
panic(err)
}
}