log101-dot-dev-services/main.go

140 lines
3.7 KiB
Go
Raw Normal View History

2024-05-17 16:01:33 +00:00
package main
import (
"errors"
2024-05-28 19:19:30 +00:00
"log"
2024-05-28 17:17:30 +00:00
"net/http"
2024-06-11 09:05:44 +00:00
"os"
2024-05-28 19:19:30 +00:00
2024-05-28 17:17:30 +00:00
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
2024-06-11 09:05:44 +00:00
"github.com/glebarez/sqlite"
2024-05-31 14:45:28 +00:00
"github.com/joho/godotenv"
2024-06-10 04:50:15 +00:00
"gorm.io/gorm"
2024-06-11 07:41:06 +00:00
"gorm.io/gorm/clause"
2024-05-30 15:42:33 +00:00
"log101-blog-services/middleware"
2024-05-17 16:01:33 +00:00
)
2024-06-10 04:50:15 +00:00
var db *gorm.DB
2024-05-28 19:19:30 +00:00
// Emoji counts for each post are retrieved in this format
2024-06-10 04:50:15 +00:00
type PostReaction struct {
2024-05-29 07:25:59 +00:00
Emoji string
TotalCount int
}
2024-06-10 04:50:15 +00:00
type EmojiReaction struct {
2024-06-11 07:41:06 +00:00
UserAnonIp string `gorm:"index:idx_anon,unqiue"`
PostId string `gorm:"index:idx_anon,unique"`
2024-06-10 04:50:15 +00:00
Emoji string
}
// Get the emoji counts foe a given post id
2024-06-10 04:50:15 +00:00
func countEmojis(postId string) (map[string]int, error) {
postReactions := []PostReaction{}
// Get the emoji counts for each emoji
2024-06-10 04:50:15 +00:00
rows := db.Model(&EmojiReaction{}).Where("post_id = ?", postId).Select([]string{"emoji", "COUNT(*) as total_count"}).Group("emoji").Find(&postReactions)
if rows.Error != nil {
return nil, errors.New("couldn't get emoji counts")
}
2024-06-10 04:50:15 +00:00
// Transform rows to map
result := make(map[string]int)
for _, reaction := range postReactions {
result[reaction.Emoji] = reaction.TotalCount
}
2024-06-10 04:50:15 +00:00
return result, nil
}
2024-05-17 16:01:33 +00:00
func main() {
2024-06-02 08:44:39 +00:00
// Load environment variables
2024-05-31 14:45:28 +00:00
err := godotenv.Load()
if err != nil {
2024-06-11 09:30:33 +00:00
log.Println("Error loading .env file")
2024-05-31 14:45:28 +00:00
}
2024-06-11 09:05:44 +00:00
dbPath := os.Getenv("DB_PATH")
db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
2024-05-28 19:19:30 +00:00
if err != nil {
2024-06-10 04:50:15 +00:00
panic("failed to connect database")
2024-05-28 19:19:30 +00:00
}
2024-06-10 04:50:15 +00:00
db.AutoMigrate(&EmojiReaction{})
2024-05-28 19:19:30 +00:00
2024-05-28 17:17:30 +00:00
r := gin.Default()
r.LoadHTMLGlob("templates/*")
2024-05-17 16:01:33 +00:00
// CORS configuration
2024-05-28 17:17:30 +00:00
corsConfig := cors.DefaultConfig()
2024-06-11 09:05:44 +00:00
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")
}
2024-06-10 04:50:15 +00:00
corsConfig.AllowHeaders = []string{"hx-current-url", "hx-request", "hx-target", "hx-trigger"}
2024-05-30 15:42:33 +00:00
// Middlewares
2024-05-28 17:17:30 +00:00
r.Use(cors.New(corsConfig))
2024-05-30 15:42:33 +00:00
r.Use(middleware.AnonymizeIPMiddleware())
2024-05-17 16:01:33 +00:00
2024-05-30 10:30:32 +00:00
blogForm := r.Group("/blog/api/")
{
// Get the emoji form, you must provide postId query parameter
blogForm.GET("/forms/emoji", func(c *gin.Context) {
postId := c.Query("postId")
// get emoji counts for each emoji
emojiCounter, err := countEmojis(postId)
if err != nil {
2024-06-11 07:41:06 +00:00
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts"})
2024-05-30 10:30:32 +00:00
return
}
// Return the html template
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{
2024-06-11 07:41:06 +00:00
"results": emojiCounter,
2024-05-30 10:30:32 +00:00
})
2024-05-28 19:19:30 +00:00
})
2024-06-11 07:41:06 +00:00
// Update the user's reaction to post, this handler will
2024-05-30 10:30:32 +00:00
// add a new entry to the database with anonymized ip
2024-06-11 07:41:06 +00:00
// updates if user reacted before
2024-05-30 10:30:32 +00:00
blogForm.POST("/forms/emoji/post", func(c *gin.Context) {
2024-06-10 04:50:15 +00:00
reactedPostId := c.PostForm("postId")
reaction := c.PostForm("emojiInput")
2024-05-30 10:30:32 +00:00
// Check if parameters are missing
2024-06-10 04:50:15 +00:00
if reactedPostId == "" || reaction == "" {
2024-06-11 07:41:06 +00:00
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "missing parameters"})
2024-05-30 10:30:32 +00:00
return
}
2024-06-11 07:41:06 +00:00
// Add the new emoji reaction to the database
result := db.Clauses(clause.OnConflict{
DoUpdates: clause.AssignmentColumns([]string{"emoji"}),
}).Create(&EmojiReaction{UserAnonIp: c.Request.RemoteAddr, Emoji: reaction, PostId: reactedPostId})
2024-06-10 04:50:15 +00:00
if result.Error != nil {
2024-06-11 07:41:06 +00:00
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error writing to database"})
2024-05-30 10:30:32 +00:00
return
}
// get emoji counts for each emoji
2024-06-10 04:50:15 +00:00
emojiCounter, err := countEmojis(reactedPostId)
2024-05-30 10:30:32 +00:00
if err != nil {
2024-06-11 07:41:06 +00:00
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts"})
2024-05-30 10:30:32 +00:00
return
}
// Return the html with the updated emoji counter
2024-06-11 07:41:06 +00:00
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"results": emojiCounter})
2024-05-30 10:30:32 +00:00
})
}
2024-05-17 16:01:33 +00:00
2024-05-30 09:52:18 +00:00
r.Run(":8000")
2024-05-17 16:01:33 +00:00
}