在Go中创建HTML服务器的基本步骤如下:
package main
import (
"log"
"net/http"
)
func main() {
// 1. 创建文件服务器,指定静态文件目录
fs := http.FileServer(http.Dir("./static"))
// 2. 注册路由,将根路径映射到文件服务器
http.Handle("/", fs)
// 3. 启动服务器监听指定端口
log.Println("服务器启动在 http://localhost:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}
目录结构示例:
project/
├── main.go
└── static/
├── index.html
├── style.css
└── script.js
如果需要更细粒度的控制,可以使用自定义处理器:
package main
import (
"log"
"net/http"
"path/filepath"
"strings"
)
func serveHTML(w http.ResponseWriter, r *http.Request) {
// 获取请求路径
path := r.URL.Path
// 默认页面
if path == "/" {
path = "/index.html"
}
// 构建文件路径
filePath := filepath.Join("./static", path)
// 根据文件扩展名设置Content-Type
if strings.HasSuffix(path, ".css") {
w.Header().Set("Content-Type", "text/css")
} else if strings.HasSuffix(path, ".js") {
w.Header().Set("Content-Type", "application/javascript")
} else if strings.HasSuffix(path, ".html") {
w.Header().Set("Content-Type", "text/html")
}
// 提供文件
http.ServeFile(w, r, filePath)
}
func main() {
http.HandleFunc("/", serveHTML)
log.Println("服务器启动在 http://localhost:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}
使用gorilla/mux路由库的示例:
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
// 静态文件服务
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static")))
// 或者指定特定路径
// r.PathPrefix("/static/").Handler(http.StripPrefix("/static/",
// http.FileServer(http.Dir("./static"))))
log.Println("服务器启动在 http://localhost:8080")
err := http.ListenAndServe(":8080", r)
if err != nil {
log.Fatal(err)
}
}
运行服务器:
go run main.go
浏览器访问 http://localhost:8080 即可查看你的HTML页面。