当前位置 博文首页 > golang文件服务器的两种方式(可以访问任何目录)

    golang文件服务器的两种方式(可以访问任何目录)

    作者:lxsky 时间:2021-02-18 06:38

    一、方法1:

    主要用到的方法是http包的FileServer,参数很简单,就是要路由的文件夹的路径。

    package main
    
    import (
      "fmt"
      "net/http"
    )
    
    func main() {
      http.Handle("/", http.FileServer(http.Dir("./")))
    
      e := http.ListenAndServe(":8080", nil)
      fmt.Println(e)
    }

    上面例子的路由只能把根目录也就是“/”目录映射出来,例如你写成”http.Handle("/files", http.FileServer(http.Dir("./")))“,就无法把通过访问”/files“把当前路径下的文件映射出来。于是就有了http包的StripPrefix方法。

    二、方法2:

    实现访问任意文件夹下面的文件。

    package main
    
    import (
      "fmt"
      "net/http"
    )
    
    func main() {
      mux := http.NewServeMux()
      mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("/"))))
      mux.Handle("/c/", http.StripPrefix("/c/", http.FileServer(http.Dir("c:"))))
      mux.Handle("/d/", http.StripPrefix("/d/", http.FileServer(http.Dir("d:"))))
      mux.Handle("/e/", http.StripPrefix("/e/", http.FileServer(http.Dir("e:"))))
      if err := http.ListenAndServe(":3008", mux); err != nil {
        log.Fatal(err)
      }
    }

    这里生成了一个ServeMux,与文件服务器无关,可以先不用关注。用这种方式,就可以把任意文件夹下的文件路由出来了。

    ps:golang实现的文件服务器

    最近在学习golang,使用golang实现了一个最简单的文件服务器,程序只有简单的十多行代码,可以编译成windows, linux, mac多平台可执行文件。

    源码

    package main
    
    import (
     "fmt"
     "net/http"
     "os"
     "path/filepath"
    )
    
    func main() {
     p, _ := filepath.Abs(filepath.Dir(os.Args[0]))
     http.Handle("/", http.FileServer(http.Dir(p)))
     err := http.ListenAndServe(":8088", nil)
     if err != nil {
     fmt.Println(err)
     }
    }

    源码解释

    os.Args[0]获取的是执行程序时的第一个参数,默认第一个参数是程序所在的目录
    filepath.Abs(filepath.Dir(os.Args[0]))是获取当前可执行程序所在的绝对路径
    http.Handle("/", http.FileServer(http.Dir(p)))是开启一个文件服务器,使用当前可执行文件所在的路径
    http.ListenAndServe(":8088", nil)是监听8088端口并开启文件服务器

    编译

    要将源码编译成不同平台的可执行文件,需要使用gox工具,使用下面的命令安装gox:

    go get github.com/mitchellh/gox

    执行成功之后,使用gox命令即可自动编译出各个平台的可执行文件,如果想为某个平台单独编译,可以使用如下方式:

    gox -os "windows linux" -arch amd64

    -os参数指定了编译平台,-arch参数指定了处理器架构

    运行

    直接打开编译出来的可执行程序,即可运行,在浏览器中访问http://ip:8088即可看到可执行文件所在的目录下的所有文件。

    js