新版本更精简:
package main
import (
"flag"
"log"
"net/http"
"os"
"io"
"path"
"strconv"
)
var dir string
var port int
var staticHandler http.Handler
// 初始化参数
func init() {
dir = path.Dir(os.Args[0])
flag.IntVar(&port, "port", 80, "服务器端口")
flag.Parse()
staticHandler = http.FileServer(http.Dir(dir))
}
func main() {
http.HandleFunc("/", StaticServer)
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
// 静态文件处理
func StaticServer(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
staticHandler.ServeHTTP(w, req)
return
}
io.WriteString(w, "hello, world!\n")
}
老版本:
package main
import (
"flag"
"log"
"net/http"
"os"
"path"
"strconv"
)
var dir string
var port int
var indexs []string
// 初始化参数
func init() {
dir = path.Dir(os.Args[0])
flag.IntVar(&port, "port", 80, "服务器端口")
flag.Parse()
indexs = []string{"index.html", "index.htm"}
}
func main() {
http.HandleFunc("/", StaticServer)
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
// 静态文件处理
func StaticServer(w http.ResponseWriter, req *http.Request) {
file := dir + req.URL.Path
fi, err := os.Stat(file)
if os.IsNotExist(err) {
http.NotFound(w, req)
return
}
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if fi.IsDir() {
if req.URL.Path[len(req.URL.Path)-1] != '/' {
http.Redirect(w, req, req.URL.Path+"/", 301)
return
}
for _, index := range indexs {
fi, err = os.Stat(file + index)
if err != nil {
continue
}
http.ServeFile(w, req, file+index)
return
}
http.NotFound(w, req)
return
}
http.ServeFile(w, req, file)
}
这是一个简化后的HTTP服务器代码示例,主要功能是提供静态文件服务。新版本移除了对多个索引文件的支持,只处理根目录的请求,并返回'hello,world!'。当请求的路径不是根目录时,服务器将直接返回静态文件。通过flag包处理命令行参数,获取服务器端口,使用http.FileServer处理静态文件请求。
887

被折叠的 条评论
为什么被折叠?



