Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Caching static resources #222

Open
juev opened this issue Apr 11, 2024 · 2 comments
Open

Caching static resources #222

juev opened this issue Apr 11, 2024 · 2 comments

Comments

@juev
Copy link

juev commented Apr 11, 2024

From #221

We need to control the caching of static resources such as images, styles, and scripts. So that when files are changed, they immediately change at the front.

There are two ways to solve the problem:

  • adding an E-Tag to static resource responses
  • dynamically forming a file name, depending on its contents.

Examples of the second implementation are available in miniflux.

@juev juev mentioned this issue Apr 11, 2024
@juev
Copy link
Author

juev commented Apr 11, 2024

😄

I asked ChatGPT how to add a tag, to which I received an answer:

package main

import (
    "crypto/md5"
    "encoding/hex"
    "net/http"
    "os"
    "io"
)

func main() {
    // Путь к статическому файлу
    staticFilePath := "path/to/static/file.txt"

    // Загрузка статического файла
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Открытие статического файла
        file, err := os.Open(staticFilePath)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer file.Close()

        // Создание хеша файла
        hash := md5.New()
        if _, err := io.Copy(hash, file); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        etag := hex.EncodeToString(hash.Sum(nil))

        // Устанавливаем заголовок ETag
        w.Header().Set("ETag", etag)

        // Проверяем If-None-Match заголовок
        if match := r.Header.Get("If-None-Match"); match == etag {
            w.WriteHeader(http.StatusNotModified)
            return
        }

        // Если не соответствует, отправляем содержимое файла
        http.ServeFile(w, r, staticFilePath)
    })

    // Старт сервера
    http.ListenAndServe(":8080", nil)
}

@juev
Copy link
Author

juev commented Apr 12, 2024

After the research, I can say that using tags does not solve the problem when using the cache on the cloudflare side.

At the moment, I see only one solution: renaming the file depending on the time of its modification or its contents.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant