我有一個函數會在每個HTTP GET請求中調用。該函數讀取文件,對該文件的內容執行一些操作,並返回這些內容的一部分字節。然後將這部分字節作爲響應主體寫入HTTP響應寫入器。Golang從文件中讀取 - 是否可以鎖定?
我是否需要在此函數中的任何步驟中使用互斥鎖來防止多個HTTP請求嘗試讀取同一文件時發生鎖定?如果是這樣,一個簡單的RWMutex鎖定文件的讀取就足夠了,因爲我實際上沒有寫入它,但是正在創建其內容的副本?
下面是函數:
// prepareIndex will grab index.html and add a nonce to the script tags for the CSP header compliance.
func prepareIndex(nonce string) []byte {
// Load index.html.
file, err := os.Open("./client/dist/index.html")
if err != nil {
log.Fatal(err)
}
// Convert to goquery document.
doc, err := goquery.NewDocumentFromReader(file)
if err != nil {
fmt.Println(err)
}
// Find all script tags and set nonce.
doc.Find("body > script").SetAttr("nonce", nonce)
// Grab the HTML string.
html, err := doc.Html()
if err != nil {
fmt.Println(err)
}
return []byte(html)
}
我也想過只加載文件一次當主開始,但我有一個問題,即只在第一次請求可以看到的數據,並在後續請求什麼也沒看見。可能是我讀文件時的錯誤。但我更喜歡我目前的做法,因爲如果index.html
有任何更改,我希望它們可以立即保存到用戶,而無需重新啓動可執行文件。
你檢查這個回購https://github.com/nightlyone/lockfile? –