spf13/afero 通用文件系统试用

以前有大概介绍过类似的几个不错的通用文件系统工具包,以下是关于spf13/afero 的试用

参考代码

package main
import (
    "io/ioutil"
    "log"
    "github.com/spf13/afero"
)
func main() {
    var appFs = afero.NewMemMapFs()
    log.Println(appFs.Name())
    appFs.Mkdir("/", 0755)
    fh, _ := appFs.Create("/demoapp.js")
    fh.WriteString("This is a test")
    fh.Close()
    file, err := appFs.Open("/demoapp.js")
    defer file.Close()
    if err != nil {
        log.Println("open file error:", err.Error())
    }
    bytes, err := ioutil.ReadAll(file)
    if err != nil {
        log.Println("read file error:", err.Error())
    }
    log.Println(string(bytes))
}

集成http server 方法

package main
import (
    "io/ioutil"
    "log"
    "net/http"
    "github.com/spf13/afero"
)
func httpFs() {
    var appFs = afero.NewMemMapFs()
    appFs.Mkdir("/", 0755)
    fh, _ := appFs.Create("/demoapp.js")
    fh.WriteString("This is a test")
    fh.Close()
    httpFs := afero.NewHttpFs(appFs)
    fileserver := http.FileServer(httpFs.Dir("/"))
    http.Handle("/", fileserver)
    http.ListenAndServe(":8090", nil)
}
func main() {
    httpFs()
}

说明

目前官方也在计划实现一个通用的文件系统,抽象层,比较期待ga,基于通用文件系统的好处是,方便测试,同时屏蔽了
对于多种异构文件系统的访问

参考资料

https://github.com/aos-dev/go-storage
https://github.com/lytics/cloudstorage
https://github.com/graymeta/stow
https://github.com/rclone/rclone
https://gocloud.dev/howto/blob/
https://github.com/spf13/afero
https://github.com/google/go-cloud/tree/master/blob
https://github.com/gregjones/httpcache

原文地址:https://www.cnblogs.com/rongfengliang/p/14236286.html