forked from bootdotdev/learn-cicd-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
98 lines (80 loc) · 2.3 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
package main
import (
"database/sql"
"embed"
"io"
"log"
"net/http"
"os"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/joho/godotenv"
"github.com/bootdotdev/learn-cicd-starter/internal/database"
_ "github.com/tursodatabase/libsql-client-go/libsql"
)
type apiConfig struct {
DB *database.Queries
}
//go:embed static/*
var staticFiles embed.FS
func main() {
err := godotenv.Load(".env")
if err != nil {
log.Printf("warning: assuming default configuration. .env unreadable: %v", err)
}
port := os.Getenv("PORT")
if port == "" {
log.Fatal("PORT environment variable is not set")
}
apiCfg := apiConfig{}
// https://github.com/libsql/libsql-client-go/#open-a-connection-to-sqld
// libsql://[your-database].turso.io?authToken=[your-auth-token]
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
log.Println("DATABASE_URL environment variable is not set")
log.Println("Running without CRUD endpoints")
} else {
db, err := sql.Open("libsql", dbURL)
if err != nil {
log.Fatal(err)
}
dbQueries := database.New(db)
apiCfg.DB = dbQueries
log.Println("Connected to database!")
}
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,
}))
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
f, err := staticFiles.Open("static/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
if _, err := io.Copy(w, f); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
v1Router := chi.NewRouter()
if apiCfg.DB != nil {
v1Router.Post("/users", apiCfg.handlerUsersCreate)
v1Router.Get("/users", apiCfg.middlewareAuth(apiCfg.handlerUsersGet))
v1Router.Get("/notes", apiCfg.middlewareAuth(apiCfg.handlerNotesGet))
v1Router.Post("/notes", apiCfg.middlewareAuth(apiCfg.handlerNotesCreate))
}
v1Router.Get("/healthz", handlerReadiness)
router.Mount("/v1", v1Router)
srv := &http.Server{
Addr: ":" + port,
Handler: router,
}
log.Printf("Serving on port: %s\n", port)
log.Fatal(srv.ListenAndServe())
}