-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
278 lines (225 loc) · 6.15 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// https://go.dev/doc/tutorial/web-service-gin
// https://www.golinuxcloud.com/golang-sqlite3/
// https://go.dev/doc/tutorial/database-access
// https://go.dev/doc/effective_go#concurrency
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/skip2/go-qrcode"
)
type Task struct {
Id float64 `json:"id"`
Title string `json:"taskTitle"`
Description string `json:"description"`
Assignee string `json:"assignee"`
Complete bool `json:"complete"`
}
type TaskJSON struct {
Title string `json:"title"`
Tasks []Task `json:"tasks"`
}
var (
InfoLogger *log.Logger
ErrorLogger *log.Logger
tasksDB TaskJSON
pathToFile string
)
var pathToQRCode = "static/qr.png"
// minutes between writing the files
const duration = 5
func initLogging() {
file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
InfoLogger = log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
ErrorLogger = log.New(file, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
}
func writeTaskDBToFile() {
output, err := json.Marshal(tasksDB)
if err != nil {
ErrorLogger.Println(err)
}
f, err := os.Create(pathToFile)
if err != nil {
ErrorLogger.Println(err)
}
defer f.Close()
_, err = f.Write(output)
if err != nil {
ErrorLogger.Println(err)
}
}
func writeToFileAsync(done <-chan bool) {
ticker := time.NewTicker(duration * time.Minute)
go func() {
for {
select {
case <-done:
InfoLogger.Println("Stopping ticker") //replace with serverlogging
ticker.Stop()
return
case <-ticker.C:
writeTaskDBToFile()
InfoLogger.Println("Wrote to file!") //replace with serverlogging
}
}
}()
}
func initTaskDB() {
dataFromFile, err := os.Open(pathToFile)
if err != nil {
panic(err)
} else {
defer dataFromFile.Close()
var data TaskJSON
decoder := json.NewDecoder(dataFromFile)
if err = decoder.Decode(&data); err != nil {
ErrorLogger.Println(err)
}
InfoLogger.Println("Imported Tasks DB:")
InfoLogger.Println(data) //replace with serverlogging
tasksDB = data
}
}
func serveFiles(c *gin.Context, contenttype string, path string) {
filename := path + c.Param("name")
_, err := os.Open(filename)
if err != nil {
ErrorLogger.Println(err)
c.JSON(404, gin.H{"error": err.Error()})
} else {
c.Header("Content-Type", contenttype)
c.File(filename)
}
}
func servePage(c *gin.Context) {
serveFiles(c, "text/html", "./static/")
}
func serveScripts(c *gin.Context) {
serveFiles(c, "text/javascript", "./static/js/")
}
func serveCSS(c *gin.Context) {
serveFiles(c, "text/css", "./static/css/")
}
func getFileName() string {
var userInput string
yn := "n"
for strings.ToLower(yn) != "y" {
fmt.Println("Please enter the filepath to grab data from: ")
fmt.Scan(&userInput)
fmt.Printf("Confirm getting data from \"%s\"? [Y/N]: ", userInput)
fmt.Scan(&yn)
for strings.ToLower(yn) != "n" && strings.ToLower(yn) != "y" {
fmt.Printf("Please enter a valid input.\nConfirm getting data from \"%s\"? [Y/N]: ", userInput)
fmt.Scan(&yn)
}
}
return userInput
}
// To be implemented: get the actual IP of the machine
func getServerIP() string {
listoFIPs, err := net.InterfaceAddrs()
if err != nil {
ErrorLogger.Println(err)
}
ipserver, _, err := net.ParseCIDR(listoFIPs[0].String())
ipOfServer := ipserver.String()
port := 80
userInput := ""
fmt.Printf("Use default value \"%s:%d\"? [Y/N]: ", ipOfServer, port)
fmt.Scan(&userInput)
for strings.ToLower(userInput) != "n" && strings.ToLower(userInput) != "y" {
fmt.Printf("Please enter a valid input.\nUse default value \"%s:%d\"? [Y/N]: ", ipOfServer, port)
fmt.Scan(&userInput)
}
if strings.ToLower(userInput) == "n" {
fmt.Print("Enter the IP address: ")
fmt.Scan(&ipOfServer)
fmt.Print("Enter port number: ")
fmt.Scan(&port)
}
return fmt.Sprintf("%s:%d", ipOfServer, port)
}
// Add Task:
// This function adds a task to the database (tasksDB) via a POST request from the user
// It replies with a 201 if created, along with the new task details
// It replies with a 406 if not created, with the error message
func addTask(c *gin.Context) {
var newTask Task
if err := c.BindJSON(&newTask); err != nil {
ErrorLogger.Println(err)
c.AbortWithStatus(http.StatusNotAcceptable)
return
}
InfoLogger.Println("Task Added:")
InfoLogger.Println(newTask)
// Add the new album to the slice.
tasksDB.Tasks = append(tasksDB.Tasks, newTask)
c.IndentedJSON(http.StatusCreated, newTask)
}
func updateTask(c *gin.Context) {
var newTask Task
if err := c.BindJSON(&newTask); err != nil {
ErrorLogger.Println(err)
c.AbortWithStatus(http.StatusNotAcceptable)
return
}
InfoLogger.Println("Task Updated:")
InfoLogger.Println(newTask)
for i := 0; i < len(tasksDB.Tasks); i++ {
if tasksDB.Tasks[i].Id == newTask.Id {
tasksDB.Tasks[i] = newTask
i = len(tasksDB.Tasks)
}
}
c.IndentedJSON(http.StatusCreated, newTask)
}
func generateQRCode(serverIP string) {
err := qrcode.WriteFile(serverIP, qrcode.Medium, 256, pathToQRCode)
if err != nil {
ErrorLogger.Println(err)
}
InfoLogger.Println("Wrote server URL to a QR code at " + pathToQRCode)
}
func initRouter() *gin.Engine {
router := gin.Default()
// Serve the index html page
router.GET("/", servePage)
// Default routes for the static stuff
router.GET("/static/css/:name", serveCSS)
router.GET("/static/js/:name", serveScripts)
router.GET("/data", func(c *gin.Context) {
c.Header("Content-Type", "application/json")
c.JSON(http.StatusOK, tasksDB)
})
router.GET("/static/qr.png", func(c *gin.Context) {
serveFiles(c, "image/png", pathToQRCode)
})
router.PATCH("/task/:id", updateTask)
router.POST("/task/", addTask)
return router
}
func main() {
gin.SetMode(gin.ReleaseMode)
initLogging()
pathToFile = getFileName()
serverIP := getServerIP()
//initalize the Tasks variable from the filepath provided
initTaskDB()
generateQRCode(serverIP)
router := initRouter()
c := make(chan bool)
writeToFileAsync(c)
InfoLogger.Println("Writing to " + pathToFile) //replace with serverlogging
fmt.Println("Running server on " + serverIP)
router.Run(serverIP)
}