package main
import (
"fmt"
"net/http"
"os"
"path"
"strings"
)
var staticfs = http.FileServer(http.Dir("D:\\code\\20160902\\src\\"))
func main() {
http.Handle("/client/",http.FileServer(http.Dir("D:\\code\\20160902\\src\\")))
http.HandleFunc("/static/",static)
http.HandleFunc("/js/",js)
http.HandleFunc("/",route)
http.ListenAndServe(":1789",nil)
}
func route(w http.ResponseWriter,r *http.Request) {
fmt.Println(r.URL)
fmt.Fprintln(w,"welcome")
r.Body.Close()
}
func static(w http.ResponseWriter,r *http.Request) {
fmt.Printf("访问静态文件:%s\n",r.URL.Path)
old := r.URL.Path
r.URL.Path = strings.Replace(old,"/static","/client",1)
staticfs.ServeHTTP(w,r)
}
func js(w http.ResponseWriter,r *http.Request) {
fmt.Printf("不能访问目录:%s\n",r.URL.Path)
old := r.URL.Path
name := path.Clean("D:/code/20160902/src" + strings.Replace(old,"/js",1))
info,err := os.Lstat(name)
if err == nil {
if !info.IsDir() {
http.ServeFile(w,r,name)
} else {
http.NotFound(w,r)
}
} else {
http.NotFound(w,r)
}
}
原文链接:https://www.f2er.com/go/188841.html