92 lines
2.2 KiB
Go
92 lines
2.2 KiB
Go
package routes
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
"strconv"
|
|
"udemy_httpserver/models"
|
|
)
|
|
|
|
func postEvent(c *gin.Context) {
|
|
var event models.Event
|
|
err := c.ShouldBindJSON(&event)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
// Todo: implement user auth
|
|
event.UserID = 0
|
|
err = event.Save()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, event)
|
|
|
|
}
|
|
|
|
func getEvents(c *gin.Context) {
|
|
events, err := models.GetAllEvents()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, events)
|
|
}
|
|
|
|
func getSingleEvent(c *gin.Context) {
|
|
eventID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
candidateEvent, err := models.FindEventById(int(eventID))
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
if candidateEvent == nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "event not found"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, *candidateEvent)
|
|
}
|
|
|
|
func updateEvent(c *gin.Context) {
|
|
// First we try to parse the json body into a struct
|
|
var event models.Event
|
|
err := c.ShouldBindJSON(&event)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
// We try to find the event by id
|
|
eventID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
// If we get a db error, we return a 500 error
|
|
candidateEvent, err := models.FindEventById(int(eventID))
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
// If the event is not found, we return a 404
|
|
if candidateEvent == nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "event not found"})
|
|
return
|
|
}
|
|
// If the event is found, we update it
|
|
event.ID = candidateEvent.ID
|
|
if event.UserID == 0 {
|
|
event.UserID = candidateEvent.UserID
|
|
}
|
|
err = event.Update()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, event)
|
|
}
|