0%

【windows技术】利用go搭建纯文件http服务器,并生成dll

利用go搭建纯文件http服务

在windows下使用go搭建纯文件服务器,并生成标准dll导出文件。

go实现HTTP文件服务器

  1. 利用net/http库文件创建http服务

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
      func serveApp(stop <-chan struct{}, port int) error {

    mux := http.NewServeMux()
    pathlist := GetLogicalDrives()//获取windows卷标
    mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("/"))))

    for _, v := range pathlist {
    fmt.Println("path:", v)
    if len(v) == 0 {
    continue
    }
    Path := "/" + v + ("/")
    Dir := v + ":"
    mux.Handle(strings.ToLower(Path), http.StripPrefix(strings.ToLower(Path), http.FileServer(http.Dir(strings.ToLower(Dir)))))
    fmt.Println("path:", Path)
    fmt.Println("Dir:", Dir)
    }
    service := string(":") + strconv.FormatInt(int64(port), 10)
    return serve(service, mux, stop)
    }
  2. 利用syscall标准系统库,遍历windows的磁盘卷标

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
      func GetLogicalDrives() []string {
    kernel32 := syscall.MustLoadDLL("kernel32.dll")//windows系统标准库
    GetLogicalDrives := kernel32.MustFindProc("GetLogicalDrives")
    n, _, _ := GetLogicalDrives.Call()
    s := FormatInt(int64(n), 2)
    var drives_all = []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
    temp := drives_all[0:len(s)]
    var d []string
    for i, v := range s {
    if v == 49 {
    l := len(s) - i - 1
    d = append(d, temp[l])
    }
    }

    for _, v := range d {
    // drives = append(drives[i:], append([]string{v}, drives[:i]...)...)
    fmt.Println(v)
    }
    return d
    }
  3. 利用http的server的停止机制,关闭http服务器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
      func serve(addr string, handler http.Handler, stop <-chan struct{}) error {
    s := http.Server{
    Addr: addr,
    Handler: handler,
    }
    go func() {
    <-stop // wait for stop signal
    s.Shutdown(context.Background()) //停止服务器
    }()
    return s.ListenAndServe()
    }

go导出dll标准导出文件

  1. 进入官网https://gcc.gnu.org/install/binaries.html,选择Microsoft -> mingw64。安装MinGW-w64。

    图1

    图2

    图3

  1. 选择安装版本,选择32位或者64位的版本进行安装,如果你生成dll想为32为位的时候就要选择32位就是i686

    图4

  2. mingw32\bin加入到环境变量中,我的电脑->高级系统设置->环境变量,在命令刚中输入gcc -v有版本信息则调试成功.

    图5

  3. 在go程序中在需要导出函数的头文件加入//export 如下

    1
    2
    3
    4
    5
    //export stop
    func stop() {
    log.Println("Stop Http!")
    close(Stopch)
    }
  4. 运行下命令就OK,或者参考下我的博客中的export.dat脚本

go build -ldflags “-s -w” -o main.dll -buildmode=c-shared main.go

  1. 在导出的.h文件中我们需要把三行注释

typedef SIZE_TYPE GoUintptr;

typedef float _Complex GoComplex64;

typedef double _Complex GoComplex128;