chore: put hx post url in a variable

This commit is contained in:
log101 2024-05-30 14:43:50 +03:00
parent 416a93d6a0
commit b13e73e726
2 changed files with 16 additions and 8 deletions

18
main.go
View File

@ -103,6 +103,13 @@ func main() {
corsConfig.AllowHeaders = []string{"hx-current-url", "hx-request"}
r.Use(cors.New(corsConfig))
var hxPostUrl string
if ginMode == gin.DebugMode {
hxPostUrl = "http://localhost:8000/blog/api/forms/emoji/post"
} else {
hxPostUrl = "https://log101.dev/blog/api/forms/emoji/post"
}
blogForm := r.Group("/blog/api/")
{
// Get the emoji form, you must provide postId query parameter
@ -112,7 +119,7 @@ func main() {
// get emoji counts for each emoji
emojiCounter, err := countEmojis(postId)
if err != nil {
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts", "postId": postId})
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts", "postId": postId, "hxPostUrl": hxPostUrl})
return
}
@ -120,6 +127,7 @@ func main() {
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{
"postId": c.Query("postId"),
"results": emojiCounter,
"hxPostUrl": hxPostUrl,
})
})
@ -132,26 +140,26 @@ func main() {
// Check if parameters are missing
if postId == "" || emoji == "" {
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "missing parameters", "postId": postId})
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "missing parameters", "postId": postId, "hxPostUrl": hxPostUrl})
return
}
// Add the new emoji entry to the database
_, err := db.Exec("INSERT INTO emoji_clicks (post_id, emoji) VALUES (?, ?)", postId, emoji)
if err != nil {
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error writing to database", "postId": postId})
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error writing to database", "postId": postId, "hxPostUrl": hxPostUrl})
return
}
// get emoji counts for each emoji
emojiCounter, err := countEmojis(postId)
if err != nil {
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts", "postId": postId})
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts", "postId": postId, "hxPostUrl": hxPostUrl})
return
}
// Return the html with the updated emoji counter
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"postId": postId, "results": emojiCounter})
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"postId": postId, "results": emojiCounter, "hxPostUrl": hxPostUrl})
})
}

View File

@ -1,4 +1,4 @@
<form hx-post="/blog/api/forms/emoji/post" hx-swap="outerHTML">
<form hx-post={{ .hxPostUrl }} hx-swap="outerHTML">
<input type="hidden" name="postId" value="{{.postId}}">
<div class="emoji-buttons-container">
{{ range .results }}