dongtui6347 2019-02-08 15:51
浏览 40

如何“禁用目录列表”和“自定义404页面”同时处理

I'm using gorilla mux for routing in my http server

https://github.com/gorilla/mux

This is my code for disable directory listing

type justFilesFilesystem struct {
  fs               http.FileSystem
  // readDirBatchSize - configuration parameter for Readdir func
  readDirBatchSize int
}

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

type neuteredStatFile struct {
  http.File
  readDirBatchSize int
}

func (e neuteredStatFile) Stat() (os.FileInfo, error) {
  s, err := e.File.Stat()
  if err != nil {
    return nil, err
  }
  if s.IsDir() {
  LOOP:
    for {
      fl, err := e.File.Readdir(e.readDirBatchSize)
      switch err {
      case io.EOF:
        break LOOP
      case nil:
        for _, f := range fl {
          if f.Name() == "" {
            return s, err
          }
        }
      default:
        return nil, err
      }
    }
    return nil, os.ErrNotExist
  }
  return s, err
}

and this is my main func

  mux := mux.NewRouter()
  // This line why not work?
  mux.NotFoundHandler = http.HandlerFunc(NotFound)

  mux.HandleFunc("/index",HandleIndex)

  fs := justFilesFilesystem{fs: http.Dir("assets"), readDirBatchSize: 0}
  staticFileHandler := http.StripPrefix("", http.FileServer(fs))
  mux.PathPrefix("").Handler(staticFileHandler).Methods("GET")

and finally my 404 handle func

func NotFound(w http.ResponseWriter, r *http.Request) {

  fmt.Fprint(w, "404")
}

The question is how to handle custom 404 page error if file not found and also disable directory listing in the same time.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么