log101-dot-dev-services/main.go
2024-06-25 15:13:24 +03:00

64 lines
1.5 KiB
Go

package main
import (
"log"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
DB "log101-blog-services/db"
"log101-blog-services/handlers"
"log101-blog-services/middleware"
)
func main() {
// Load environment variables
err := godotenv.Load()
if err != nil {
log.Println("Error loading .env file")
}
// initialize db
DB.InitDB()
r := gin.Default()
r.LoadHTMLGlob("templates/*")
// CORS configuration
corsConfig := cors.DefaultConfig()
corsConfig.AllowOrigins = []string{"https://log101.dev", "http://blog.log101.local", "https://blog.log101.dev"}
ginMode := gin.Mode()
if ginMode == gin.DebugMode {
corsConfig.AllowOrigins = append(corsConfig.AllowOrigins, "http://localhost:4321")
}
// these are required for htmx to work
corsConfig.AllowHeaders = []string{"hx-current-url", "hx-request", "hx-target", "hx-trigger"}
// Middlewares
r.Use(cors.New(corsConfig))
r.Use(middleware.AnonymizeIPMiddleware())
blog := r.Group("/api/blog/")
{
// Get the emoji form, postId query parameter is required
blog.GET("/forms/emoji", handlers.GetEmojiForm)
// Update the user's reaction to post, this handler will
// add a new entry to the database with anonymized ip
// updates if user reacted before
blog.POST("/forms/emoji", handlers.PostEmojiForm)
// Get the comments for a post, postId query parameter is required
blog.GET("/comments", handlers.GetComments)
// Drop comment on a post, postId and comment body is required
blog.POST("/comments", handlers.PostComment)
}
r.Run(":8000")
}