GoLang 实现一个最简单的http文件服务器

How to use

  • 关闭防火墙
  • 运行 GoServer.exe,不要关闭命令行窗口
  • 将本地文件放到 go 文件根目录的 file 文件夹中即可实现内网共享文件

GoServer.go

package main

import (
	"log"
	"net/http"
	"os"
)

func main() {

	os.Mkdir("file", 0777)

	http.Handle("/pollux/", http.StripPrefix("/pollux/", http.FileServer(http.Dir("file"))))
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
	
}


func FileServer

TIM截图20170303113018.png

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.To use the operating system's file system implementation, use http.Dir:

func StripPrefix

TIM截图20170303112931.png

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.

http://localhost:8080/pollux/