go語言實現一個簡單的文件服務器 http.FileServer


package main

import (
	"flag"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
	"strings"
	"time"
)

func main() {

	root := flag.String("p", "", "file server root directory")
	flag.Parse()

	if len(*root) == 0 {
		log.Fatalln("file server root directory not set")
	}

	if !strings.HasPrefix(*root, "/") {
		log.Fatalln("file server root directory not begin with '/'")
	}

	if !strings.HasSuffix(*root, "/") {
		log.Fatalln("file server root directory not end with '/'")
	}

	p, h := NewFileHandle(*root)
	r := httprouter.New()
	r.GET(p, LogHandle(h))

	log.Fatalln(http.ListenAndServe(":8080", r))
}

func NewFileHandle(path string) (string, httprouter.Handle) {
	return fmt.Sprintf("%s*files", path), func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		http.StripPrefix(path, http.FileServer(http.Dir(path))).ServeHTTP(w, r)
	}
}

func LogHandle(handle httprouter.Handle) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		now := time.Now()
		handle(w, r, p)
		log.Printf("%s %s %s done in %v", r.RemoteAddr, r.Method, r.URL.Path, time.Since(now))
	}
}

准備測試文件

編譯運行

用瀏覽器訪問







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM