Mensa-API/server/mensa.go

60 lines
1.0 KiB
Go
Raw Normal View History

2024-09-15 16:57:03 +00:00
package server
2024-09-15 17:10:19 +00:00
import (
"github.com/LeRoid-hub/Mensa-API/cache"
"github.com/LeRoid-hub/Mensa-API/fetch"
"github.com/LeRoid-hub/Mensa-API/scrape"
"github.com/gin-gonic/gin"
)
func mensa(c *gin.Context) {
mensa := c.Param("mensa")
if mensa == "" {
c.JSON(400, gin.H{
"error": "mensa is required",
})
return
}
city := c.Param("city")
if city == "" {
c.JSON(400, gin.H{
"error": "city is required",
})
return
}
if cache.HasCacheData(city + "/" + mensa) {
2024-09-15 19:39:17 +00:00
cacheData, err := cache.GetCacheData(city + "/" + mensa)
if err != nil {
c.JSON(500, gin.H{
"error": err.Error(),
})
return
}
c.JSON(200, cacheData)
2024-09-15 17:10:19 +00:00
return
}
2024-09-15 18:26:08 +00:00
resp, err := fetch.Fetch(city + "/" + mensa)
2024-09-15 17:10:19 +00:00
if err != nil {
c.JSON(500, gin.H{
"error": err.Error(),
})
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
c.JSON(500, gin.H{
"error": "status code is not 200",
})
return
}
2024-09-15 18:26:08 +00:00
scraped := scrape.ScrapeMensa(resp.Body)
2024-09-15 19:39:17 +00:00
cache.SetCacheData(city+"/"+mensa, scraped)
2024-09-15 18:26:08 +00:00
2024-09-15 17:10:19 +00:00
c.JSON(200, scraped)
}