threadr-rewritten/handlers/like.go

78 lines
2.5 KiB
Go

package handlers
import (
"log"
"net/http"
"strconv"
"threadr/models"
"github.com/gorilla/sessions"
)
func LikeHandler(app *App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
session := r.Context().Value("session").(*sessions.Session)
userID, ok := session.Values["user_id"].(int)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
postIDStr := r.FormValue("post_id")
postID, err := strconv.Atoi(postIDStr)
if err != nil {
http.Error(w, "Invalid post ID", http.StatusBadRequest)
return
}
likeType := r.FormValue("type")
if likeType != "like" && likeType != "dislike" {
http.Error(w, "Invalid like type", http.StatusBadRequest)
return
}
existingLike, err := models.GetLikeByPostAndUser(app.DB, postID, userID)
if err != nil {
log.Printf("Error checking existing like: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
if existingLike != nil {
if existingLike.Type == likeType {
err = models.DeleteLike(app.DB, postID, userID)
if err != nil {
log.Printf("Error deleting like: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
} else {
err = models.UpdateLikeType(app.DB, postID, userID, likeType)
if err != nil {
log.Printf("Error updating like: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
} else {
like := models.Like{
PostID: postID,
UserID: userID,
Type: likeType,
}
err = models.CreateLike(app.DB, like)
if err != nil {
log.Printf("Error creating like: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
}