-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (77 loc) · 2.1 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
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"os"
"sync"
)
type Question struct {
ID int `json:"id"`
Question string `json:"question"`
Answer string `json:"answer"`
}
type Quiz struct {
Title string `json:"title"`
Author string `json:"author"`
Questions []Question `json:"questions"`
Flag string `json:"flag"`
TimeoutAmount int `json:"timeout_amount"`
}
type QuizServer struct {
Host string
Port string
QuizObject *Quiz
}
func NewQuizServer(host string, port string, quizObj *Quiz) *QuizServer {
return &QuizServer{
Host: host,
Port: port,
QuizObject: quizObj,
}
}
var (
logFile *os.File
logMutex sync.Mutex
logFileName string = "quiz_attempts.json"
listeningHost string = os.Getenv("HOST")
listeningPort string = os.Getenv("PORT")
)
func (server *QuizServer) Run() {
log.Printf("Quiz Server listening on %s:%s...\n", server.Host, server.Port)
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%s", server.Host, server.Port))
if err != nil {
log.Fatalln("[tcp-listening] error occured during listening:", err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatalln("[tcp-accept-conn] error occured during accepting new conn:", err)
}
log.Printf("received connection from %s\n", conn.RemoteAddr().String())
go handleRequest(conn, server.QuizObject)
}
}
func main() {
quiz := &Quiz{}
questionFilePath := "./question.json"
// questionFilePath := os.Args[1]
questionFile, err := os.ReadFile(questionFilePath)
if err != nil {
log.Fatalln("[question-init] failed to open questions file:", err)
}
err = json.Unmarshal(questionFile, quiz)
if err != nil {
log.Fatalln("[question-init] failed to unmarshal question json:", err.Error())
}
log.Println(quiz)
logFile, err = os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("[logging-init] failed to open the log file: %v\n", err)
}
defer logFile.Close()
quizServer := NewQuizServer(listeningHost, listeningPort, quiz)
quizServer.Run()
}