-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (79 loc) · 2.09 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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/indenigrate/rssagg/internal/database"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
type apiConfig struct {
DB *database.Queries
}
func main() {
//loading .env (environment variables)
errgodot := godotenv.Load(".env")
if errgodot != nil {
log.Fatal("Error loading .env file")
}
//retrieving PORT variable data
portString := os.Getenv("PORT")
if portString == "" {
log.Fatal("PORT is not found in the environment")
}
fmt.Println("Port:", portString)
//import DB url
dbURL := os.Getenv("DB_URL")
if dbURL == "" {
log.Fatal("DB_URL is not found in the environment")
}
//connect to DB
conn, err := sql.Open("postgres", dbURL)
if err != nil {
log.Fatal("Can't connnect to DataBase ", err)
}
apiCfg := apiConfig{
DB: database.New(conn),
}
//initiating router
router := chi.NewRouter()
//initiating cors
router.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"*"},
ExposedHeaders: []string{"Link"},
AllowCredentials: false,
MaxAge: 300,
}))
//using seperate handler
v1Router := chi.NewRouter()
v1Router.Get("/healthz", handlerReadiness)
// v1Router.HandleFunc("/healthz", handlerReadiness)
v1Router.Get("/err", handlerErr)
v1Router.Post("/users", apiCfg.handlerCreateUser)
router.Mount("/v1", v1Router)
//initiate server properties
srv := &http.Server{
Handler: router,
Addr: ":" + portString,
}
log.Printf("Server starting on port %v\n", portString)
// router.Get("/", func(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintln(w, "Hello, World!")
// log.Println("Request for GET executed")
// })
// router.Post("/", func(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintln(w, "Hello, World!")
// log.Println("Request for POST executed")
// w.WriteHeader(500)
// })
err = srv.ListenAndServe()
if err != nil {
log.Fatalf("Error starting server %v\n", err)
}
}