-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (72 loc) · 1.88 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/joho/godotenv"
)
// Example rest api with chi
// https://github.com/go-chi/chi/blob/master/_examples/rest/main.go#L189
func main() {
loadEnv()
// Init DB connection
GetDatabaseConnection()
// Init router
r := chi.NewRouter()
r.Mount("/api", getApiSubrouter())
fmt.Println("Server started and ready on port 3001")
http.ListenAndServe(":3001", r)
// Close DB connection
GetDatabaseConnection().Close()
}
func getApiSubrouter() *chi.Mux {
r := chi.NewRouter()
r.Get("/", hello)
r.Post("/login", login)
r.Post("/register", register)
r.Mount("/account", getAccountSubrouter())
r.Mount("/service", getServiceSubrouter())
return r
}
func hello(w http.ResponseWriter, r *http.Request) {
RespondWithJSON(w, http.StatusOK, map[string]string{"message": "Hello, World!"})
}
func loadEnv() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func login(w http.ResponseWriter, r *http.Request) {
var u User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&u); err != nil {
RespondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
u.UUID = r.Context().Value("uuid").(string)
if IsAuthenticated(u) {
RespondWithError(w, http.StatusBadRequest, "Failed to login")
return
}
sessionId := CreateSession(u)
if sessionId == "" {
RespondWithError(w, http.StatusFailedDependency, "Failed to create session")
}
}
type registerRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
func register(w http.ResponseWriter, r *http.Request) {
var req registerRequest
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&req); err != nil {
RespondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
AddUser(req.Username, req.Password)
RespoondWithSuccess(w)
}