package main import ( "log" "net/http" "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" "log101-blog-services/models" ) 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, you must provide postId query parameter 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) blog.GET("/comments", func(c *gin.Context) { db := DB.GetDB() postId := c.Query("postId") comments := []models.Comment{} rows := db.Where("post_id = ?", postId).Find(&comments) if rows.Error != nil { c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) } c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) }) blog.POST("/comments", func(c *gin.Context) { db := DB.GetDB() postId := c.PostForm("postId") commentBody := c.PostForm("commentBody") username := c.PostForm("username") if postId == "" || commentBody == "" { c.HTML(http.StatusBadRequest, "comment_form.tmpl", gin.H{}) } result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username}) if result.Error != nil { c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{}) } c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{}) }) } r.Run(":8000") }