-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
130 lines (97 loc) · 2.83 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
package main
import (
"encoding/json"
"fmt"
"fud_library/auth"
"fud_library/book"
"fud_library/utils"
"log"
"net/http"
"os"
"strings"
"time"
socketio "github.com/googollee/go-socket.io"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"github.com/rs/cors"
)
func Router(server *socketio.Server) *mux.Router {
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/", VersionHandler)
r.HandleFunc("/posts", book.CreatePost).Methods("POST")
r.HandleFunc("/posts", book.GetPosts).Methods("GET")
r.HandleFunc("/sendotp", auth.SendOTP).Methods("POST")
r.HandleFunc("/verifyotp", auth.VerifyOTP).Methods("GET")
return r
}
func main() {
// Socket events
var Server = socketio.NewServer(nil)
err := godotenv.Load(".env")
if err != nil {
log.Printf("Error loading .env file: %v", err)
}
fmt.Println("Environment variables successfully loaded. Starting application...")
if err = utils.ConnectToDB(os.Getenv("CLUSTER_URL")); err != nil {
fmt.Println("Could not connect to MongoDB")
}
// get PORT from environment variables
port, _ := os.LookupEnv("PORT")
if port == "" {
port = "8000"
}
r := Router(Server)
c := cors.AllowAll()
h := RequestDurationMiddleware(r)
srv := &http.Server{
Handler: handlers.LoggingHandler(os.Stdout, c.Handler(h)),
Addr: ":" + port,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
//nolint:errcheck //CODEI8: ignore error check
go Server.Serve()
fmt.Println("Socket Served")
defer Server.Close()
fmt.Println("Fud Book API - running on port ", port)
//nolint:gocritic //CODEI8: please provide soln -> lint throw exitAfterDefer: log.Fatal will exit, and `defer Server.Close()` will not run
log.Fatal(srv.ListenAndServe())
}
func VersionHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Fud Book API - Version 0.01\n")
}
func RequestDurationMiddleware(h http.Handler) http.Handler {
const durationLimit = 10
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
h.ServeHTTP(w, r)
duration := time.Since(start)
postToSlack := func() {
m := make(map[string]interface{})
m["timeTaken"] = duration.Seconds()
if duration.Seconds() < durationLimit {
return
}
scheme := "http"
if r.TLS != nil {
scheme += "s"
}
m["endpoint"] = fmt.Sprintf("%s://%s%s", scheme, r.Host, r.URL.Path)
m["timeTaken"] = duration.Seconds()
b, _ := json.Marshal(m)
resp, err := http.Post("https://companyfiles.zuri.chat/api/v1/slack/message", "application/json", strings.NewReader(string(b)))
if err != nil {
return
}
if resp.StatusCode != 200 {
fmt.Printf("got error %d", resp.StatusCode)
}
defer resp.Body.Close()
}
if strings.Contains(r.Host, "api.zuri.chat") {
go postToSlack()
}
})
}