duanbo1659 2019-05-14 14:25
浏览 358

golang FileServer设置目录

I have a Golang Shell with a FileServer function that I want to be able to change the src directory. Here is what I have:

func Server() {
    wdir, _ := os.Getwd()
    m := http.NewServeMux()
    fs := http.FileServer(http.Dir(wdir))
    m.Handle("/", http.StripPrefix("/", fs))
    s := http.Server{Addr: ":8000", Handler: m}
    m.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) {
        s.Shutdown(context.Background())
    })
    if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        log.Fatal(err)
    }
    log.Printf("Finished")
}

I have it this way so that if I get to shutdown, the FileServer closes. But no matter from what path I launch Server(), the path remains always the same.

So if from the shell I cd into another folder and launch Server(), I will still get the files from the directory where the executable is.

What I want is that if I run the shell from /home/user/Downloads/shell and inside the shell I cd into /opt, the files to show in the server are the ones in /opt, not the ones in /home/user/Downloads/shell

  • 写回答

1条回答 默认 最新

  • drwj4061 2019-05-14 17:10
    关注

    You can bring in the FileServer path as a flag and use that to create the FileServer.

    http.FileServer(http.Dir(path + "/opt")).
    

    Please check the flag library provided by go.

    And in the terminal you can feed pwd into that flag value

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!