Server side If-Modified-Since cache

This commit is contained in:
Brieuc Dubois 2024-01-04 14:13:27 +01:00
parent a3f2c07217
commit 505e5aae75
3 changed files with 39 additions and 3 deletions

View File

@ -3,9 +3,11 @@ package handlers
import ( import (
"fmt" "fmt"
"strconv" "strconv"
"time"
"git.bhasher.com/bhasher/focus/backend/db" "git.bhasher.com/bhasher/focus/backend/db"
"git.bhasher.com/bhasher/focus/backend/types" "git.bhasher.com/bhasher/focus/backend/types"
"git.bhasher.com/bhasher/focus/backend/utils"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
@ -21,8 +23,16 @@ func projectsRouter(router fiber.Router) error {
return nil return nil
} }
var projectsLastEdit time.Time;
func GetAllProjects(c *fiber.Ctx) error { func GetAllProjects(c *fiber.Ctx) error {
isCached, err := utils.Cache(c, projectsLastEdit);
if err == nil && isCached {
return nil;
}
projects, err := db.GetAllProjects() projects, err := db.GetAllProjects()
currentTime := time.Now();
if err != nil { if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "Cannot retrieve projects", "error": "Cannot retrieve projects",
@ -30,7 +40,13 @@ func GetAllProjects(c *fiber.Ctx) error {
}) })
} }
return c.Status(fiber.StatusOK).JSON(projects) err = c.Status(fiber.StatusOK).JSON(projects)
if err != nil {
return err;
}
projectsLastEdit = currentTime;
return nil;
} }
func GetProject(c *fiber.Ctx) error { func GetProject(c *fiber.Ctx) error {

View File

@ -6,7 +6,6 @@ import (
"os" "os"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cache"
"github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/cors"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
@ -37,7 +36,7 @@ func main() {
AllowHeaders: "Origin, Content-Type, Accept", AllowHeaders: "Origin, Content-Type, Accept",
})) }))
app.Use(cache.New()) // app.Use(cache.New())
handlers.APIRouter(app.Group("/api")) handlers.APIRouter(app.Group("/api"))

21
backend/utils/cache.go Normal file
View File

@ -0,0 +1,21 @@
package utils
import (
"time"
"github.com/gofiber/fiber/v2"
)
func Cache(c *fiber.Ctx, lastEdit time.Time) (bool, error) {
clientLast, err := time.Parse(time.RFC1123, c.Get("If-Modified-Since"))
if err != nil {
return false, err
}
if clientLast.Before(lastEdit) {
c.SendStatus(fiber.StatusNotModified)
return true, nil
}
return false, nil
}