本文是《Go语言100个实战案例》系列之《网络与并发篇》的第一篇。我们将从零开始,用Go语言构建一个基础的 HTTP 服务器,掌握 Go 在服务端开发中的关键能力。
一、为什么选择 Go 来开发 HTTP 服务?
Go 语言天生支持网络编程,其标准库 net/http
内置了完整的 HTTP 协议处理能力,语法简洁、性能优越,非常适合用于构建高性能 Web 服务和 API 服务。
优势包括:
- • 内置 HTTP 支持
- • 简洁的并发模型(Goroutine)
- • 部署简单,编译为单个可执行文件
- • 高性能、跨平台
二、基础目标:构建一个本地 HTTP 服务
✅ 功能需求:
- • 启动后监听本地端口(例如 8080)
- • 支持根路径
/
请求并返回"Hello, World!" - • 支持
/time
请求,返回当前服务器时间 - • 日志输出每个请求的路径和来源 IP
三、完整示例代码
go
package main
import (
"fmt"
"log"
"net/http"
"time"
)
// 根路径处理器
func helloHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("访问路径:%s,来源:%s\n", r.URL.Path, r.RemoteAddr)
fmt.Fprintf(w, "Hello, World! 👋")
}
// /time 路径处理器
func timeHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("访问路径:%s,来源:%s\n", r.URL.Path, r.RemoteAddr)
currentTime := time.Now().Format("2006-01-02 15:04:05")
fmt.Fprintf(w, "当前服务器时间:%s", currentTime)
}
func main() {
// 注册路由处理器
http.HandleFunc("/", helloHandler)
http.HandleFunc("/time", timeHandler)
// 启动 HTTP 服务
port := ":8080"
log.Printf("启动 HTTP 服务,监听端口 %s\n", port)
err := http.ListenAndServe(port, nil)
if err != nil {
log.Fatalf("服务器启动失败:%v", err)
}
}
四、运行与测试
运行命令:
go
go run main.go
访问方式:
-
- 打开浏览器访问:
-
- • http://localhost:8080/ 会显示 `Hello, World!
- • http://localhost:8080/time 会显示当前服务器时间
-
- 使用 curl 测试:
bash
curl http://localhost:8080/
curl http://localhost:8080/time
五、进阶建议
这个 HTTP 服务虽然简单,但它是后续进阶的基础。你可以继续扩展它:
- • 使用
http.ServeMux
自定义路由器 - • 增加静态文件服务(如 HTML/CSS/JS)
- • 加入 JSON 接口支持
- • 加入日志中间件
- • 将服务并发能力与 Goroutine、Channel 结合
六、小结
通过本篇,你已经成功用 Go 构建了一个完整的 HTTP 服务。这个项目虽然小巧,但是搭建微服务、开发 REST API、构建高并发服务的基础之一。