go语言在同一局域网下共享某一文件夹

package main

import (
	"fmt"
	"net"
	"net/http"
)

const (
	port          = ":8888"
	dir  http.Dir = `D:\\FileRecv\\MobileFile\\Image`
)

func main() {
	// 设置静态文件目录和文件列表中间件
	http.Handle("/", http.FileServer(dir))
	// 获取局域网IPv4地址
	ip, err := getLocalIPv4()
	if err != nil {
		panic(err)
	}
	fmt.Printf("服务已经启动,访问地址:http://%s%s\n", ip, port)
	// 启动监听服务
	err = http.ListenAndServe(port, nil)
	if err != nil {
		panic(err)
	}
}

// 获取局域网IPV4地址
func getLocalIPv4() (string, error) {
	interfaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}
	for i := range interfaces {
		if interfaces[i].Name == "WLAN" {
			addrs, err := interfaces[i].Addrs()
			if err != nil {
				return "", err
			}
			for _, addr := range addrs {
				if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						return ipnet.IP.String(), nil
					}
				}
			}
		}
	}
	return "", fmt.Errorf("未找到IPv4地址")
}

你可能感兴趣的:(golang,开发语言,后端)