-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (54 loc) · 1.29 KB
/
main.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
package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
melody "gopkg.in/olahol/melody.v1"
)
var title = "Hello TECH(K)NOW Day"
func main() {
log.Println("Start web service")
r := gin.Default()
m := melody.New()
r.Static("/assets", "./assets")
r.LoadHTMLGlob("templates/*")
r.GET("/", index)
r.GET("/login", loginPage)
r.POST("/login", login)
r.GET("/chat", chat)
r.GET("/ws", func(c *gin.Context) {
m.HandleRequest(c.Writer, c.Request)
})
m.HandleMessage(func(s *melody.Session, msg []byte) {
m.Broadcast(msg)
})
r.Run(":8080")
}
func index(c *gin.Context) {
c.HTML(http.StatusOK, "index.html.tmpl", gin.H{
"Title": title,
})
}
func login(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
log.Println("username:", username)
if username == "Benjamin" && password == "1234" {
c.SetCookie("username", username, 60, "/", "localhost", false, true)
c.String(http.StatusOK, "Hi "+username)
} else {
c.String(http.StatusOK, fmt.Sprintf("%s password error", username))
}
}
func loginPage(c *gin.Context) {
c.HTML(http.StatusOK, "login.html.tmpl", gin.H{
"Title": title,
})
}
func chat(c *gin.Context) {
username, _ := c.Cookie("username")
c.HTML(http.StatusOK, "chat.html.tmpl", gin.H{
"username": username,
})
}