github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgNet/kmgHttp/FileServer.go (about)

     1  package kmgHttp
     2  
     3  import (
     4  	"net/http"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/bronze1man/kmg/kmgFile"
    10  	"strconv"
    11  )
    12  
    13  // 向http默认服务器加入一个本地文件或目录
    14  func MustAddFileToHttpPathToDefaultServer(httpPath string, localFilePath string) {
    15  	MustAddFileToHttpPathToServeMux(http.DefaultServeMux, httpPath, localFilePath)
    16  }
    17  
    18  func MustAddFileToHttpPathToServeMux(mux *http.ServeMux, httpPath string, localFilePath string) {
    19  	localFilePath, err := kmgFile.Realpath(localFilePath)
    20  	//_, err := os.Stat(localFilePath)
    21  	if err != nil {
    22  		panic(err)
    23  	}
    24  	if !strings.HasPrefix(httpPath, "/") {
    25  		httpPath = "/" + httpPath
    26  	}
    27  	if !strings.HasSuffix(httpPath, "/") {
    28  		httpPath = httpPath + "/"
    29  	}
    30  	mux.HandleFunc(httpPath, CompressHandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    31  		urlPath := req.URL.Path
    32  		relPath := strings.TrimPrefix(urlPath, httpPath)
    33  		filePath := filepath.Join(localFilePath, relPath)
    34  		fi, err := os.Stat(filePath)
    35  		if err != nil {
    36  			http.NotFound(w, req)
    37  			return
    38  		}
    39  		if fi.IsDir() {
    40  			http.NotFound(w, req)
    41  			return
    42  		}
    43  		http.ServeFile(w, req, filePath)
    44  	}))
    45  	/*
    46  		if fi.IsDir() {
    47  			if !strings.HasSuffix(httpPath, "/") {
    48  				httpPath += "/"
    49  			}
    50  			mux.Handle(httpPath, http.StripPrefix(httpPath, http.FileServer(http.Dir(localFilePath))))
    51  		} else {
    52  			mux.HandleFunc(httpPath, func(w http.ResponseWriter, req *http.Request) {
    53  				http.ServeFile(w, req, localFilePath)
    54  			})
    55  		}
    56  	*/
    57  	return
    58  }
    59  
    60  func MustAddContentToDefaultServer(uri string, content []byte) {
    61  	uri = "/" + strings.Trim(uri, "/")
    62  	http.DefaultServeMux.HandleFunc(uri, func(w http.ResponseWriter, req *http.Request) {
    63  		w.Header().Set("Cache-Control", "max-age=3600")
    64  		w.Header().Set("Content-Length", strconv.Itoa(len(content)))
    65  		w.Write(content)
    66  	})
    67  }