2026-10-19 13:20:16
使用Golang的net/http包创建基础HTTP服务非常简单,以下是分步实现指南及关键概念说明:
1. 创建最简单的HTTP服务以下代码启动一个监听3000端口的Web服务器,访问根路径/返回固定内容:
package mainimport ( "fmt" "net/http")func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, 你好!这是你的第一个Go Web服务。")}func main() { http.HandleFunc("/", helloHandler) // 注册路由和处理函数 fmt.Println("服务器正在启动,访问关键点:
w http.ResponseWriter:用于构造HTTP响应。
r *http.Request:包含请求信息(如方法、路径、头部等)。
为不同路径注册不同处理函数,实现差异化响应:
func main() { // 根路径 http.HandleFunc("/", helloHandler) // 关于页面 http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "关于页面:这是一个Go写的简单服务。") }) // API接口 http.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `{"message": "数据返回成功", "code": 0}`) }) http.ListenAndServe(":3000", nil)}注意:
通过r.Method判断请求类型,实现不同逻辑:
func formHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { // 返回表单页面 fmt.Fprintf(w, ` <form method="POST"> <button type="submit">提交POST请求</button> </form> `) } else if r.Method == "POST" { // 处理POST请求 fmt.Fprintf(w, "收到POST请求,处理成功!") }}func main() { http.HandleFunc("/form", formHandler) http.ListenAndServe(":3000", nil)}场景:
通过http.FileServer和http.StripPrefix托管静态资源(如HTML、CSS、JS):
func main() { // 创建文件服务器,指向public目录 fs := http.FileServer(http.Dir("public")) // 注册路由,去掉URL前缀/static/ http.Handle("/static/", http.StripPrefix("/static/", fs)) http.ListenAndServe(":3000", nil)}目录结构:
project/├── main.go└── public/ └── index.html访问方式:
整合上述功能,实现一个包含多路由、方法处理和静态文件服务的HTTP服务:
package mainimport ( "fmt" "net/http")func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, 你好!这是你的第一个Go Web服务。")}func aboutHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "关于页面:这是一个Go写的简单服务。")}func apiDataHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `{"message": "数据返回成功", "code": 0}`)}func formHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { fmt.Fprintf(w, ` <form method="POST"> <button type="submit">提交POST请求</button> </form> `) } else if r.Method == "POST" { fmt.Fprintf(w, "收到POST请求,处理成功!") }}func main() { // 路由注册 http.HandleFunc("/", helloHandler) http.HandleFunc("/about", aboutHandler) http.HandleFunc("/api/data", apiDataHandler) http.HandleFunc("/form", formHandler) // 静态文件服务 fs := http.FileServer(http.Dir("public")) http.Handle("/static/", http.StripPrefix("/static/", fs)) // 启动服务器 fmt.Println("服务器正在启动,访问通过net/http包,你可以快速实现:
适用场景:学习Go Web开发、小型项目或需要快速验证的场景。对于复杂需求(如中间件、路由嵌套),可引入Gin、Echo等框架。