-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
177 lines (148 loc) · 4.81 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/gocql/gocql"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
type Payload struct {
// UserEmail string `json:"userEmail"`
// UserNN string `json:"userNN"`
UserPk int64 `json:"userPk"`
}
type AddMessageTmp struct {
UserPk int64
MsgContent string
}
type SendMessageTmp struct {
Id string
UserPk int64
MsgContent string
Datetime string
IsChecked bool
}
func main() {
app := fiber.New()
app.Use(cors.New())
// 실라 디비와 연결하기
cluster := gocql.NewCluster(os.Getenv("DB_HOST"))
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: os.Getenv("DB_USERNAME"),
Password: os.Getenv("DB_PASSWORD"),
}
session, err := cluster.CreateSession()
if err != nil {
log.Fatal(err)
}
defer session.Close()
// alog라는 keyspace가 있는지 확인하고 없으면 만듭니다.
err = session.Query("CREATE KEYSPACE IF NOT EXISTS alog WITH REPLICATION={'class' : 'SimpleStrategy', 'replication_factor' : 1};").Exec()
if err != nil {
log.Fatal(err)
}
// noti라는 table이 있는지 확인하고 없으면 만듭니다.
err = session.Query("CREATE TABLE IF NOT EXISTS alog.notification (id uuid, UserPk bigint, MsgContent text, Datetime timestamp, IsChecked boolean, PRIMARY KEY (id, UserPk));").Exec()
if err != nil {
log.Fatal(err)
}
/*
* testing
*/
app.Get("/api/noti/hello", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
/*
* 프론트에서 호출하여 UserPk에 해당하는 전체 메시지 반환
*/
app.Get("/api/noti", func(c *fiber.Ctx) error {
log.Println("Get /api/noti")
jwt := c.Get("Authorization")
// Split the JWT into three parts
parts := strings.Split(jwt, ".")
if len(parts) != 3 {
return fmt.Errorf("invalid JWT format")
}
// Decode the second part, which is the payload
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return fmt.Errorf("failed to decode payload: %v", err)
}
// Unmarshal the payload into a struct
p := &Payload{}
err = json.Unmarshal(payload, &p)
if err != nil {
return fmt.Errorf("failed to unmarshal payload: %v", err)
}
scanner := session.Query("SELECT id, UserPk, MsgContent, Datetime, IsChecked FROM alog.notification WHERE UserPk=?;", p.UserPk).Iter().Scanner()
returnlist := []*SendMessageTmp{}
for scanner.Next() {
datetime := time.Time{}
msg := &SendMessageTmp{}
err = scanner.Scan(&msg.Id, &msg.UserPk, &msg.MsgContent, &datetime, &msg.IsChecked)
if err != nil {
log.Fatal(err)
}
msg.Datetime = datetime.Format(time.RFC3339)
returnlist = append(returnlist, msg)
}
// scanner.Err() closes the iterator, so scanner nor iter should be used afterwards.
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return c.JSON(fiber.Map{"data": returnlist})
})
app.Put("/api/noti", func(c *fiber.Ctx) error {
m := c.Queries()
id := m["id"]
log.Println("Get /api/noti : ", id)
jwt := c.Get("Authorization")
// Split the JWT into three parts
parts := strings.Split(jwt, ".")
if len(parts) != 3 {
return fmt.Errorf("invalid JWT format")
}
// Decode the second part, which is the payload
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return fmt.Errorf("failed to decode payload: %v", err)
}
// Unmarshal the payload into a struct
p := &Payload{}
err = json.Unmarshal(payload, &p)
if err != nil {
return fmt.Errorf("failed to unmarshal payload: %v", err)
}
// TODO update noti set IsChecked = true where id = id
if err := session.Query("UPDATE alog.notification SET IsChecked = true WHERE id=? and UserPk=?;", id, p.UserPk).Exec(); err != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
return c.Status(fiber.StatusOK).SendString("ok")
})
/*
* 서비스에서 호출 하여 메시지를 받아서 db에 넣는것 -> UserPk, message, time, IsChecked
*/
app.Post("/api/noti", func(c *fiber.Ctx) error {
p := new(AddMessageTmp)
if err := c.BodyParser(p); err != nil {
return err
}
log.Println("POST /api/noti : ", p.UserPk, p.MsgContent)
now := time.Now().UTC()
u, err := gocql.RandomUUID()
if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
// TODO insert into noti (_pk , UserPk, message, time, IsChecked) values (p.userPk, p.MsgContent, now, false)
if err := session.Query("INSERT INTO alog.notification (id, UserPk, MsgContent, Datetime, IsChecked) VALUES (?, ?, ?, ?, ?);", u.String(), p.UserPk, p.MsgContent, now, false).Exec(); err != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
return c.Status(fiber.StatusOK).SendString("ok")
})
app.Listen(":" + os.Getenv("HOST_PORT"))
}