如何用Golang创建基础HTTP服务 使用net/http包快速入门

如何用Golang创建基础HTTP服务 使用net/http包快速入门
最新回答
吐舌奶包吴市长

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("服务器正在启动,访问
http://localhost:3000"
) http.ListenAndServe(":3000", nil) // 启动服务器}

关键点:

  • http.HandleFunc:注册路由路径(如/)和对应的处理函数。
  • helloHandler:处理函数接收两个参数:

    w http.ResponseWriter:用于构造HTTP响应。

    r *http.Request:包含请求信息(如方法、路径、头部等)。

  • http.ListenAndServe:启动服务器,监听指定端口(如3000),nil表示使用默认多路复用器。
2. 多路由与路径处理

为不同路径注册不同处理函数,实现差异化响应:

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)}

注意:

  • 路由匹配是精确的,不支持通配符(如需复杂路由,可使用第三方库如gorilla/mux)。
3. 处理请求方法(GET/POST)

通过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)}

场景:

  • 访问/form显示表单,提交后触发POST请求并返回响应。
4. 提供静态文件服务

通过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

访问方式:

  • 访问/static/index.html即可获取public/index.html文件内容。
5. 完整示例代码

整合上述功能,实现一个包含多路由、方法处理和静态文件服务的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("服务器正在启动,访问
http://localhost:3000"
) http.ListenAndServe(":3000", nil)}总结

通过net/http包,你可以快速实现:

  • 路由注册:http.HandleFunc绑定路径和处理函数。
  • 请求处理:通过r.Method区分请求类型。
  • 静态资源托管:http.FileServer+http.StripPrefix映射本地目录。
  • 服务器启动:http.ListenAndServe监听端口。

适用场景:学习Go Web开发、小型项目或需要快速验证的场景。对于复杂需求(如中间件、路由嵌套),可引入Gin、Echo等框架。