-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (66 loc) · 1.91 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
package main
import (
"context"
"log"
"net/http"
"os"
"sistema-maika-chat/clients"
"sistema-maika-chat/handlers"
"time"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/redis/go-redis/extra/redisotel/v9"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
func root(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("The Maika Chat is listening!"))
}
func main() {
dbClient, err := sqlx.Connect("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal("Error conecting to postgres", err)
}
clients.DB = dbClient
defer clients.DB.Close()
if err := clients.DB.Ping(); err != nil {
log.Fatal("Could not ping to postgres", err)
} else {
log.Println("Succesfully connected to Postgres")
}
opt, err := redis.ParseURL(os.Getenv("REDIS_URL"))
if err != nil {
log.Fatal("Error parsing redis url", err)
}
clients.Redis = redis.NewClient(opt)
if err := redisotel.InstrumentTracing(clients.Redis); err != nil {
log.Panic(err)
}
if err := redisotel.InstrumentMetrics(clients.Redis); err != nil {
log.Panic(err)
}
ctx := context.Background()
response, err := clients.Redis.Ping(ctx).Result()
if err != nil {
log.Fatal("Could not ping to redis", err)
} else {
log.Println("Succesfully connected to redis", response)
}
router := http.NewServeMux()
router.HandleFunc("/", root)
router.HandleFunc("/ws", handlers.HandleWebsocketConnection)
router.HandleFunc("POST /message", handlers.HandlePostMessage)
router.HandleFunc("DELETE /message", handlers.HandleDeleteMessage)
handler := http.Handler(router)
handler = otelhttp.NewHandler(handler, "maika-chat")
httpServer := &http.Server{
Addr: ":8080",
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
Handler: handler,
}
if err := httpServer.ListenAndServe(); err != nil {
log.Println(err.Error())
}
}