-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
66 lines (55 loc) · 1.61 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 (
"bytes"
"crypto/rand"
"fmt"
"net/http"
"time"
stdLogger "log"
"github.com/oleg-polivannyi/synth-log-test/config"
"github.com/oleg-polivannyi/synth-log-test/log"
)
func main() {
cfg := config.LoadConfig()
logger, err := log.NewLogger(&cfg)
if err != nil {
stdLogger.Fatal("Could not initialize logger:", err)
}
http.HandleFunc("/", handleRequest(logger, cfg))
go sendRequestsPeriodically(logger, cfg)
logger.Info("Starting server on port", cfg.Port)
if err := http.ListenAndServe(":"+cfg.Port, nil); err != nil {
logger.Error("Server failed:", err)
}
}
func handleRequest(logger *log.Logger, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
logger.Info("Received request from ", r.RemoteAddr, " message: ", r.Form.Get("message"))
fmt.Fprintf(w, "Hello from %s!", cfg.Tag)
}
}
func sendRequestsPeriodically(logger *log.Logger, cfg config.Config) {
ticker := time.NewTicker(time.Duration(60/cfg.EventFrequency) * time.Second)
defer ticker.Stop()
for {
<-ticker.C
message := generateGUID()
form := fmt.Sprintf("message=%s", message)
resp, err := http.Post(cfg.TargetURL, "application/x-www-form-urlencoded", bytes.NewBufferString(form))
if err != nil {
logger.Error("Failed to send request:", err)
} else {
logger.Info("Sent request to ", cfg.TargetURL, " with response status: ", resp.Status)
resp.Body.Close()
}
}
}
func generateGUID() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return ""
}
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}