forked from fwhezfwhez/tcpx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
66 lines (58 loc) · 1.2 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
package main
import (
"fmt"
"github.com/CocoKelam/tcpx"
//"tcpx"
)
func main() {
srv := tcpx.NewTcpX(nil)
srv.Use("before-login", beforeLogin)
srv.AddHandler(1, login)
fmt.Println("tcp listen on :8080")
if e := srv.ListenAndServe("tcp", ":8080"); e != nil {
panic(e)
}
}
func beforeLogin(c *tcpx.Context) {
header, e := tcpx.HeaderOf(c.Stream)
if e != nil {
c.JSON(tcpx.SERVER_ERROR, tcpx.H{
"message": e.Error(),
})
c.Abort()
return
}
auth, ok := header["Authorization"]
if !ok {
c.JSON(tcpx.NOT_AUTH, tcpx.H{
"message": "not found auth in header['Authorization']",
})
c.Abort()
return
}
if auth != "a client secret key" {
c.JSON(tcpx.NOT_AUTH, tcpx.H{
"message": "auth fail, invalid client secret key",
})
c.Abort()
return
}
c.Next()
fmt.Println("after login, do log")
}
func login(c *tcpx.Context) {
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
var user User
if _, e := c.Bind(&user); e != nil {
c.JSON(2, tcpx.H{
"message": e.Error(),
})
return
}
fmt.Println("login success")
token := "AD2KQ33M3ZI56EJ127AI5DK4EO31Q6QWE8ZK75D43ADF412G"
c.JSON(2, tcpx.H{"message": "login success", "token": token})
}