Server side If-Modified-Since cache
This commit is contained in:
parent
a3f2c07217
commit
505e5aae75
|
@ -3,9 +3,11 @@ package handlers
|
|||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.bhasher.com/bhasher/focus/backend/db"
|
||||
"git.bhasher.com/bhasher/focus/backend/types"
|
||||
"git.bhasher.com/bhasher/focus/backend/utils"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
|
@ -21,8 +23,16 @@ func projectsRouter(router fiber.Router) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
var projectsLastEdit time.Time;
|
||||
|
||||
func GetAllProjects(c *fiber.Ctx) error {
|
||||
isCached, err := utils.Cache(c, projectsLastEdit);
|
||||
if err == nil && isCached {
|
||||
return nil;
|
||||
}
|
||||
|
||||
projects, err := db.GetAllProjects()
|
||||
currentTime := time.Now();
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"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 {
|
||||
|
|
|
@ -6,7 +6,6 @@ import (
|
|||
"os"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cache"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
|
||||
|
@ -37,7 +36,7 @@ func main() {
|
|||
AllowHeaders: "Origin, Content-Type, Accept",
|
||||
}))
|
||||
|
||||
app.Use(cache.New())
|
||||
// app.Use(cache.New())
|
||||
|
||||
handlers.APIRouter(app.Group("/api"))
|
||||
|
||||
|
|
|
@ -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
|
||||
}
|
Loading…
Reference in New Issue