100 lines
2.2 KiB
Go
100 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/joho/godotenv"
|
|
"github.com/uptrace/bun/extra/bundebug"
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
"fr.latosa-escrima/api"
|
|
"fr.latosa-escrima/core"
|
|
"fr.latosa-escrima/utils"
|
|
"github.com/gorilla/csrf"
|
|
)
|
|
|
|
var CORS_AllowOrigin string
|
|
|
|
func handler(w http.ResponseWriter, r *http.Request) {
|
|
fmt.Fprintf(w, "<html><body><h1>Hello, World!</h1></body></html>")
|
|
}
|
|
|
|
func main() {
|
|
err := godotenv.Load()
|
|
if err != nil {
|
|
log.Fatalf("Error loading .env file: %v", err)
|
|
}
|
|
environ := os.Getenv("ENVIRONMENT")
|
|
|
|
port := os.Getenv("BACKEND_DOCKER_PORT")
|
|
hostname := os.Getenv("DATABASE_HOSTNAME")
|
|
postgres_port := os.Getenv("POSTGRES_DOCKER_PORT")
|
|
if environ == "DEV" {
|
|
port = os.Getenv("BACKEND_PORT")
|
|
hostname = "localhost"
|
|
postgres_port = os.Getenv("POSTGRES_PORT")
|
|
}
|
|
|
|
dsn := core.DSN{
|
|
Hostname: hostname,
|
|
Port: postgres_port,
|
|
DBName: os.Getenv("POSTGRES_DB"),
|
|
User: os.Getenv("POSTGRES_USER"),
|
|
Password: os.Getenv("POSTGRES_PASSWORD"),
|
|
}
|
|
fmt.Println(dsn.ToString())
|
|
core.DB, err = core.InitDatabase(dsn)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
core.DB.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))
|
|
|
|
defer core.DB.Close()
|
|
|
|
CSRFMiddleware := csrf.Protect(
|
|
core.CSRF_KEY,
|
|
csrf.Secure(environ != "DEV"),
|
|
csrf.HttpOnly(true),
|
|
)
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
baseRoutes := map[string]core.Handler{
|
|
"/": {
|
|
Handler: handler,
|
|
Middlewares: []core.Middleware{api.Methods("GET"),
|
|
api.HasPermissions("blogs", "insert"),
|
|
api.AuthJWT,
|
|
}},
|
|
"/contact": {
|
|
Handler: api.HandleContact,
|
|
Middlewares: []core.Middleware{api.Methods("POST"), CSRFMiddleware},
|
|
},
|
|
"/csrf-token": {
|
|
Handler: api.HandleCSRF,
|
|
Middlewares: []core.Middleware{api.Methods("GET"), CSRFMiddleware},
|
|
},
|
|
}
|
|
routes := utils.MergeMaps(
|
|
baseRoutes,
|
|
api.UserRoutes,
|
|
api.BlogsRoutes,
|
|
api.EventsRoutes,
|
|
api.MediaRoutes,
|
|
api.PermissionsRoutes,
|
|
api.RolesRoutes,
|
|
api.ShortcodesRoutes)
|
|
core.HandleRoutes(mux, routes)
|
|
|
|
fmt.Printf("Serving on port %s\n", port)
|
|
err = http.ListenAndServe(fmt.Sprintf(":%s", port), api.CORS(mux))
|
|
if err != nil {
|
|
fmt.Printf("Error starting server: %s\n", err)
|
|
}
|
|
}
|