package main
import (
"fmt"
"io"
"net/http"
"os"
"runtime"
"strings"
"time"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// 控制台打印请求信息
fmt.Printf("[%s][%s] %s %s\n",
time.Now().Format("2006/01/02 15:04:05"),
r.RemoteAddr,
r.Method,
r.URL.Path)
// 添加HTTP头 Server: go1.16.2
w.Header().Set("Server", runtime.Version())
// 获取要求的文件路径
path := "./html" + r.URL.Path
// 如果是目录则访问 index.html 文件
if strings.HasSuffix(path, "/") {
path += "index.html"
}
// 读取要请求的文件内容
bytes, err := os.ReadFile(path)
// 处理错误
if err != nil {
// 控制台显示错误信息
fmt.Println("Error:", err)
if os.IsNotExist(err) {
w.WriteHeader(http.StatusNotFound)
io.WriteString(w, "404 Not Found")
} else if os.IsPermission(err) {
w.WriteHeader(http.StatusForbidden)
io.WriteString(w, "403 Forbidden")
} else {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, "500 Internal Server Error")
}
return
}
// 发送文件内容
w.Write(bytes)
})
// 监听8080端口
http.ListenAndServe(":8080", nil)
}
本文标签: Golang
暂无评论,赶紧发表一下你的看法吧。