小巧HTTP静态资源服务器

分类:技术文档 - Golang | 阅读(366) | 发布于:2019-03-04 17:06

工作中难免遇到使用http去传输一些文件,为了避免每次去下载安装一些软件,自己使用golang快速实现一个。双击打开,填入端口号及路径,直接访问浏览器“http://IP:端口”号即可浏览文件

代码如下:(后面提供windows版本下载地址)

package main

import (
	"os"
	"fmt"
	"time"
	"strings"
	"net/http"
	"path/filepath"
)

func main() {

	//设定默认值
	defaultPort, defaultDir := "8080", getCurrentDirectory()
	port, dir := "", ""

	if len(os.Args) > 1 {
		//使用命令行直接指定参数
		for k, v := range os.Args {
			if k == 0 {
				continue
			}

			if v == "" {
				continue
			}

			val := strings.Split(v, "=")

			if strings.ToLower(val[0]) == "-port" {
				port = strings.ToLower(val[1])
				continue
			}

			if strings.ToLower(val[0]) == "-dir" {
				dir = strings.ToLower(val[1])
				continue
			}
		}
	}

	//Usage
	if len(os.Args) < 3 || port == "" || dir == "" {
		fmt.Println("Usage: " + os.Args[0] + " [-port=?] [-dir=?] ")
	}

	//使用命令交互模式指定参数port
	if port == "" {
		fmt.Println("Please input http port [default is \"" + defaultPort + "\"] :")
		fmt.Scanln(&port)
		if port == "" {
			port = defaultPort
		}
	}

	//使用命令交互模式指定参数dir
	if dir == "" {
		fmt.Println("Please input http static resource directory [default is \"" + defaultDir + "\"] :")
		fmt.Scanln(&dir)
		if dir == "" {
			dir = defaultDir
		}
	}

	fmt.Println("HttpServer is running at port:" + port + " directory:" + dir)
	fmt.Println("Input \"Ctrl+C\" to stop it.")
	http.Handle("/", http.FileServer(http.Dir(dir)))
	err := http.ListenAndServe(":"+port, nil)
	if err != nil {
		fmt.Println(err)
		time.Sleep(time.Duration(5) * time.Second)
	}
}

//获取当前程序所在目录
func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		return "./"
	}
	return strings.Replace(dir, "\\", "/", -1)
}

自己编译命令:

go build -o fileServer.exe fileServer.go

直接下载Windows版本:fileServer.exe

标签: