-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (71 loc) · 2.08 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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/joho/godotenv"
"github.com/matthewsah/twitter_backend_clone/internal/database"
_ "github.com/lib/pq"
)
type apiConfig struct {
DB *database.Queries
}
func main() {
fmt.Println("hello world")
godotenv.Load(".env")
portString := os.Getenv("PORT")
if portString == "" {
log.Fatal("Port is not found in the environment")
}
dbURL := os.Getenv("DB_URL")
if dbURL == "" {
log.Fatal("DB URL is not found in the environment")
}
conn, err := sql.Open("postgres", dbURL)
if err != nil {
log.Fatal("unable to connect to postgresql database", err)
}
apiCfg := apiConfig{
DB: database.New(conn),
}
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"},
AllowCredentials: false,
MaxAge: 300,
}))
v1Router := chi.NewRouter()
// test to make sure server is running and can serve requests
v1Router.Get("/healthz", handlerReadiness)
v1Router.Get("/err", handlerErr)
// add a new user
v1Router.Post("/users", apiCfg.handlerCreateUser)
// get a new user by apikey
v1Router.Get("/users", apiCfg.middlewareAuth(apiCfg.handlerGetUser))
// follow a user
v1Router.Post("/follow", apiCfg.middlewareAuth(apiCfg.handlerCreateFollow))
// get accounts/user that the user follows
v1Router.Get("/follow", apiCfg.middlewareAuth(apiCfg.handlerGetFollows))
// unfollow a user
v1Router.Delete("/follow/{followID}", apiCfg.middlewareAuth(apiCfg.handlerDeleteFollow))
// post a tweet
v1Router.Post("/tweets", apiCfg.middlewareAuth(apiCfg.handlerCreateTweet))
v1Router.Get("/home", apiCfg.middlewareAuth(apiCfg.handlerGetFeed))
router.Mount("/v1", v1Router)
srv := &http.Server{
Handler: router,
Addr: ":" + portString,
}
log.Printf("server starting on port %v", portString)
err = srv.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}