简介

Go 标准库的 net/http 包提供了强大而简洁的 HTTP 服务器实现。本文将展示如何用最少的代码启动一个可用的 HTTP 服务器。

最小实现

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    })

    fmt.Println("Server started at :8080")
    http.ListenAndServe(":8080", nil)
}

代码解析

路由注册

http.HandleFunc("/", handler)

HandleFunc 将一个 URL 路径映射到一个处理函数。第一个参数是路径模式,第二个参数是 func(ResponseWriter, *Request) 类型的函数。

启动服务器

http.ListenAndServe(":8080", nil)
  • 第一个参数:监听地址(:8080 表示监听所有网卡的 8080 端口)
  • 第二个参数:自定义 Handler(传 nil 时使用 DefaultServeMux

扩展:带路由的版本

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type Response struct {
    Message string `json:"message"`
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home Page")
}

func apiHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(Response{Message: "API response"})
}

func main() {
    http.HandleFunc("/", homeHandler)
    http.HandleFunc("/api", apiHandler)

    fmt.Println("Server running at http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

关键点

  1. 简洁性:Go 的 HTTP 服务器可以用不到 10 行代码启动
  2. 标准库:无需依赖第三方框架即可构建生产级服务
  3. 并发处理:每个请求会在独立的 goroutine 中处理

延伸阅读

总结

Go 的 net/http 包设计简洁而强大,适合快速构建 HTTP 服务。理解基础用法后,可以根据需求选择是否引入框架(如 Gin、Echo)。