Skip to content
This repository has been archived by the owner on Dec 16, 2022. It is now read-only.

Set Last-Modified header for several HTML pages #34

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions database/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ func (msg *Message) CreatedAtRFC3339() string {
return sqlTimeToGoTime(msg.CreatedAt).Format(time.RFC3339)
}

func (msg *Message) GetUpdatedAt() time.Time {
return sqlTimeToGoTime(msg.UpdatedAt)
}

func sqlTimeToGoTime(sqlTime string) time.Time {
t, err := time.Parse("2006-01-02T15:04:05Z", sqlTime)
if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ func (h *Handler) LatestMessagesByRoom(w http.ResponseWriter, r *http.Request) {
return
}

setLastModifiedAt(w, messages)
data := &template.ListTemplateData{
Messages: messages,
Rooms: h.AllRooms(),
Expand Down Expand Up @@ -132,6 +133,7 @@ func (h *Handler) LatestMessagesByAuthor(w http.ResponseWriter, r *http.Request)
return
}

setLastModifiedAt(w, messages)
data := &template.ListTemplateData{
Messages: messages,
Rooms: h.AllRooms(),
Expand Down Expand Up @@ -189,6 +191,7 @@ func (h *Handler) MessageContext(w http.ResponseWriter, r *http.Request) {
return
}

setLastModifiedAt(w, subsequentMessages)
data := &template.ShowTemplateData{
PriorMessages: priorMessages,
Message: *message,
Expand Down
12 changes: 12 additions & 0 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,15 @@ func (h *Handler) FetchAndCacheGet(r *http.Request, key string, f messagesGetFun

return message, err
}

// Set Last-Modified header
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
func setLastModifiedAt(w http.ResponseWriter, messages []database.Message) {
latestTimestamp := time.Unix(0, 0)
for _, message := range messages {
if updatedAt := message.GetUpdatedAt(); updatedAt.After(latestTimestamp) {
latestTimestamp = updatedAt
}
}
w.Header().Set("Last-Modified", latestTimestamp.Format(time.RFC1123))
}