Golang实现HTTP服务器的完整示例代码
Golang实现HTTP服务器的完整示例代码 在Go语言最早的演讲之一中,Rob Pike展示了一个大约10行Go代码的“健壮且高性能”HTTP服务器示例。这很巧妙,但我一直不确定它是否实用。在我看来,它似乎能处理WebAPI类型的函数,但没有提供基本的文件内容交付功能。
是否存在一个针对近期或当前Go版本编写的、更完整的现代HTTP服务器版本?我很想获得一个链接……
你说得对,Rob Pike 在早期 Go 语言演讲中展示的那个 10 行 HTTP 服务器是一个简化示例,并不适合实际生产环境使用。不过,现在确实有用 Go 编写的、更现代的、功能更完整的 HTTP 服务器版本,它们同时提供了 Web API 功能和文件内容交付能力。
是的,理想情况下,我希望找到一个大约30行左右的示例,它既能处理一些Web API,也能处理传统的静态内容交付。在本世纪初,我们经常在Java层中使用Java Servlet,但只是将静态内容交付分派给Apache或类似的服务器。我更倾向于保持纯粹的、符合Go语言习惯的写法。
有合适的示例链接吗?
嗯,http.ServeFile 让提供静态内容变得非常简单:

使用 Golang HTTP 提供静态内容
一个关于如何通过 Golang 提供受保护的静态内容的快速简易教程。
你可能也会对这个有趣的指南感兴趣:

编写 Web 应用程序 - Go 编程语言
或者这个:
HTTP 服务器 - Go Web 示例
这个示例展示了如何使用 net/http 包来创建一个带有处理程序和静态文件的 HTTP 服务器。
以下是基于Go 1.21+的完整HTTP服务器示例,包含API路由、静态文件服务和中间件支持:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"time"
)
// API响应结构
type APIResponse struct {
Status string `json:"status"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// 日志中间件
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s %s", r.Method, r.RequestURI, time.Since(start))
})
}
// 静态文件处理器
func staticFileHandler(staticDir string) http.Handler {
fs := http.FileServer(http.Dir(staticDir))
return http.StripPrefix("/static/", fs)
}
// API处理器
func apiHandler(w http.ResponseWriter, r *http.Request) {
response := APIResponse{
Status: "success",
Message: "API endpoint working",
Data: map[string]interface{}{
"timestamp": time.Now().Unix(),
"method": r.Method,
},
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
// 健康检查端点
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "healthy",
"time": time.Now().UTC().Format(time.RFC3339),
})
}
func main() {
// 创建路由器
mux := http.NewServeMux()
// 静态文件服务(假设static目录存在)
staticDir := "./static"
if _, err := os.Stat(staticDir); !os.IsNotExist(err) {
mux.Handle("/static/", staticFileHandler(staticDir))
log.Printf("Static file serving enabled from %s", staticDir)
}
// API路由
mux.HandleFunc("/api/", apiHandler)
mux.HandleFunc("/health", healthHandler)
// 根路径处理
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
fmt.Fprintf(w, `
<!DOCTYPE html>
<html>
<head>
<title>Go HTTP Server</title>
</head>
<body>
<h1>Go HTTP Server Running</h1>
<ul>
<li><a href="/api/test">API Endpoint</a></li>
<li><a href="/health">Health Check</a></li>
<li><a href="/static/">Static Files</a></li>
</ul>
</body>
</html>`)
})
// 配置服务器
server := &http.Server{
Addr: ":8080",
Handler: loggingMiddleware(mux),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
log.Printf("Server starting on http://localhost%s", server.Addr)
log.Printf("Available endpoints:")
log.Printf(" GET / - Welcome page")
log.Printf(" GET /api/* - API endpoints")
log.Printf(" GET /health - Health check")
log.Printf(" GET /static/* - Static files")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server failed: %v", err)
}
}
创建静态文件目录和示例文件:
# 创建目录结构
mkdir -p static/css static/js static/images
# 创建示例CSS文件
cat > static/css/style.css << 'EOF'
body {
font-family: Arial, sans-serif;
margin: 40px;
}
EOF
# 创建示例HTML文件
cat > static/example.html << 'EOF'
<!DOCTYPE html>
<html>
<head>
<title>Static File Example</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<h1>Static File Served Successfully</h1>
<p>This file is served from the static directory.</p>
</body>
</html>
EOF
运行服务器:
go run server.go
访问以下端点进行测试:
http://localhost:8080/- 主页面http://localhost:8080/api/test- API端点http://localhost:8080/health- 健康检查http://localhost:8080/static/example.html- 静态文件
这个实现提供了:
- 结构化路由管理
- 静态文件服务(支持HTML/CSS/JS/图片)
- JSON API响应
- 请求日志中间件
- 超时配置
- 健康检查端点
- 错误处理
对于生产环境,建议添加TLS支持、指标收集和优雅关闭功能。

