2026-02-21 06:10:22 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
2026-02-21 09:48:05 +00:00
|
|
|
"net/http"
|
2026-02-21 06:10:22 +00:00
|
|
|
|
|
|
|
|
"github.com/spf13/afero"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
//基于内存的文件读写
|
|
|
|
|
fs := afero.NewMemMapFs()
|
|
|
|
|
|
|
|
|
|
afero.WriteFile(fs, "poem.txt", []byte("月光光,照大床"), 0644)
|
|
|
|
|
|
|
|
|
|
data, err := afero.ReadFile(fs, "poem.txt")
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fmt.Println(string(data))
|
2026-02-21 06:45:22 +00:00
|
|
|
|
|
|
|
|
//真实文件系统
|
|
|
|
|
fs = afero.NewOsFs()
|
|
|
|
|
|
|
|
|
|
afero.WriteFile(fs, "poem.txt", []byte("月光光,照大床(文件系统)"), 0644)
|
|
|
|
|
|
|
|
|
|
data, err = afero.ReadFile(fs, "poem.txt")
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fmt.Println(string(data))
|
|
|
|
|
|
|
|
|
|
//拷贝文件
|
|
|
|
|
err = afero.WriteFile(fs, "poem_copy.txt", data, 0644)
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//限定根目录
|
|
|
|
|
bfs := afero.NewBasePathFs(afero.NewOsFs(), "/home/yy/project")
|
|
|
|
|
if _, err := bfs.Open("/etc/passwd"); err != nil {
|
|
|
|
|
fmt.Println(err.Error())
|
|
|
|
|
}
|
2026-02-21 09:48:05 +00:00
|
|
|
|
|
|
|
|
//当作http.FileSystem
|
|
|
|
|
memFs := afero.NewMemMapFs()
|
|
|
|
|
afero.WriteFile(memFs, "index.html", []byte("<h1>Afero in web</h1>"), 0644)
|
|
|
|
|
|
|
|
|
|
httpFs := afero.NewHttpFs(memFs)
|
|
|
|
|
http.Handle("/", http.FileServer(httpFs))
|
|
|
|
|
//显示index.html文件内容
|
|
|
|
|
|
|
|
|
|
http.ListenAndServe(":8080", nil)
|
2026-02-21 06:10:22 +00:00
|
|
|
}
|