Skip to content

golang自定义FileSystem

net/http.FileServer 作为静态文件服务器的时候,默认会显示目录列表,如果不想要显示目录列表的话,可以通过自定义FileSystem 来实现。

自定义FileSystem 只要实现Open 方法即可

package http

import "net/http"

type CustomFileSystem struct {
	Fs http.FileSystem
}

func (cfs CustomFileSystem) Open(name string) (http.File, error) {
	f, err := cfs.Fs.Open(name)
	if err != nil {
		return nil, err
	}

	s, err := f.Stat()
	if err != nil {
		return nil, err
	}

	if s.IsDir() {
		index := name + "/index.html"
		if _, err := cfs.Fs.Open(index); err != nil {
			closeErr := f.Close()
			if closeErr != nil {
				return nil, closeErr
			}

			return nil, err
		}
	}
	return f, nil
}

使用方式,如下

defaultFs := http.Dir("./ui/static/")

fileServer := http.FileServer(myHttp.CustomFileSystem{Fs: defaultFs})

mux.Handle("/static/", http.StripPrefix("/static", fileServer))
Published ingolang

Be First to Comment

Leave a Reply

Your email address will not be published.