-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (67 loc) · 1.93 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"
"time"
"github.com/abrl91/golang-rss-scraper/internal/database"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
// holds the connection to the database
type apiConfig struct {
DB *database.Queries
}
func main() {
godotenv.Load(".env")
port := os.Getenv("PORT")
if port == "" {
log.Fatal("PORT must be set")
}
dbUrl := os.Getenv("DB_URL")
if dbUrl == "" {
log.Fatal("DB_URL must be set")
}
connection, err := sql.Open("postgres", dbUrl)
if err != nil {
log.Fatal("Can't connect to the DB", err)
}
db := database.New(connection)
apiCfg := &apiConfig{
DB: db,
}
go startScraping(db, 10, time.Minute)
router := chi.NewRouter()
router.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"*"},
ExposedHeaders: []string{"Link"},
MaxAge: 300,
}))
v1Router := chi.NewRouter()
v1Router.Get("/health", handlerReadiness)
v1Router.Get("/error", handleError)
v1Router.Post("/users", apiCfg.handlerCreateUser)
v1Router.Get("/users", apiCfg.middlewareAuth(apiCfg.handlerGetUserByApiKey))
v1Router.Get("/posts", apiCfg.middlewareAuth(apiCfg.handlerGetPosts))
v1Router.Get("/feeds", apiCfg.handlerGetFeeds)
v1Router.Post("/feeds", apiCfg.middlewareAuth(apiCfg.handlerCreateFeed))
v1Router.Post("/feeds/follows", apiCfg.middlewareAuth(apiCfg.handlerCreateFeedFollow))
v1Router.Get("/feeds/follows", apiCfg.middlewareAuth(apiCfg.handlerGetFeedFollow))
v1Router.Delete("/feeds/follows/{id}", apiCfg.middlewareAuth(apiCfg.handlerDeleteFeedFollow))
router.Mount("/v1", v1Router)
server := &http.Server{
Handler: router,
Addr: ":" + port,
}
fmt.Printf("server starting on port %v ", port)
err = server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}