74 lines
1.7 KiB
Go
74 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/pocketbase/pocketbase"
|
|
"github.com/pocketbase/pocketbase/apis"
|
|
"github.com/pocketbase/pocketbase/core"
|
|
"github.com/pocketbase/pocketbase/lubinas"
|
|
)
|
|
|
|
func main() {
|
|
app := pocketbase.New()
|
|
|
|
app.RootCmd.ParseFlags(os.Args[1:])
|
|
|
|
app.OnServe().BindFunc(func(se *core.ServeEvent) error {
|
|
se.Router.GET("/{path...}", apis.Static(lubinas.DistDirFS, true)).
|
|
BindFunc(func(e *core.RequestEvent) error {
|
|
// ignore root path
|
|
if e.Request.PathValue(apis.StaticWildcardParam) != "" {
|
|
e.Response.Header().Set("Cache-Control", "max-age=1209600, stale-while-revalidate=86400")
|
|
}
|
|
|
|
return e.Next()
|
|
}).
|
|
Bind(apis.Gzip())
|
|
|
|
return se.Next()
|
|
})
|
|
|
|
app.OnRecordViewRequest().BindFunc(addLastModified)
|
|
|
|
app.OnRecordUpdateRequest().BindFunc(ifUnmodifiedSince)
|
|
|
|
app.OnRecordDeleteRequest().BindFunc(ifUnmodifiedSince)
|
|
|
|
if err := app.Start(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func addLastModified(e *core.RecordRequestEvent) error {
|
|
updated := e.Record.GetString("updated")
|
|
|
|
if updated != "" {
|
|
e.Response.Header().Add("Last-Modified", updated)
|
|
}
|
|
|
|
return e.Next()
|
|
}
|
|
|
|
func ifUnmodifiedSince(e *core.RecordRequestEvent) error {
|
|
updated := e.Record.GetString("updated")
|
|
|
|
if updated != "" {
|
|
header := e.Request.Header.Get("If-Unmodified-Since")
|
|
|
|
if header == "" || header != updated {
|
|
e.Response.Header().Add("Last-Modified", updated)
|
|
|
|
if header == "" {
|
|
return e.Error(http.StatusPreconditionRequired, "Header If-Unmodified-Since is required", nil)
|
|
} else if header != updated {
|
|
return e.Error(http.StatusPreconditionFailed, "Record was modified after retrieval", nil)
|
|
}
|
|
}
|
|
}
|
|
|
|
return e.Next()
|
|
}
|