且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止使用Golang服务器访问文件夹中的文件

更新时间:2023-09-19 23:41:46

如果您想使用 http 包阻止目录,那么这可能对您有用:

If you want to block a directory using http package, maybe this will be useful to you :

https://groups.google.com/forum/#!topic/golang-nuts/bStLPdIVM6w

package main

import (
  "net/http"
  "os"
)

type justFilesFilesystem struct {
  fs http.FileSystem
}

func (fs justFilesFilesystem) Open(name string) (http.File, error) {
  f, err := fs.fs.Open(name)
  if err != nil {
      return nil, err
  }
  return neuteredReaddirFile{f}, nil
}

type neuteredReaddirFile struct {
  http.File
}

func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
  return nil, nil
}

func main() {
  fs := justFilesFilesystem{http.Dir("/tmp/")}
  http.ListenAndServe(":8080", http.FileServer(fs))
}