1 回答

TA貢獻1813條經(jīng)驗 獲得超2個贊
網(wǎng)易娛樂.文件服務器函數(shù)只返回一個處理程序。因此,它不會阻塞文件系統(tǒng)。此處的問題可能與文件的偏移量有關(guān)。我已經(jīng)在我的機器中嘗試過,它工作沒有任何問題。
我已經(jīng)修改了你的代碼;
package main
import (
"net/http"
"os"
"time"
)
func main() {
t := time.NewTicker(time.Second)
defer t.Stop()
go func() {
srv := http.FileServer(http.Dir("./test"))
http.ListenAndServe(":8080", srv)
}()
for {
select {
case <-t.C:
appendToFile()
}
}
}
func appendToFile() {
f, err := os.OpenFile("./test/index.html", os.O_RDWR, 0644)
if err != nil {
panic(err)
}
defer f.Close()
// This assumes that the file ends with </body></html>
f.Seek(-16, 2)
if _, err = f.WriteString("test test test\n"); err != nil {
panic(err)
}
if _, err = f.WriteString("</body></html>\n"); err != nil {
panic(err)
}
}
在索引中.html我最初放置空白文檔,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body></html>
PS:最好先檢查偏移量,然后將字符串寫入該位置。
- 1 回答
- 0 關(guān)注
- 95 瀏覽
添加回答
舉報