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

Commit

Permalink
Set Last-Modified header for several HTML pages
Browse files Browse the repository at this point in the history
  • Loading branch information
parkr authored May 9, 2022
1 parent 31adb89 commit 572fac9
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
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))
}

0 comments on commit 572fac9

Please sign in to comment.