手把手教你用Go编写第一个HTTP服务器:零基础也能搞定
引言
HTTP 服务器是云原生应用的基础。无论是微服务、API 网关还是 Web 应用,都离不开 HTTP 服务器。本文将手把手教你用 Go 语言编写第一个 HTTP 服务器,从最简单的 Hello World 到完整的 RESTful API,让你零基础也能快速上手。
一、Go 标准库 net/http 基础
1.1 最简单的 HTTP 服务器
让我们从最基础的例子开始:
packagemainimport("fmt""net/http")funcmain(){// 注册路由处理函数http.HandleFunc("/",func(w http.ResponseWriter,r*http.Request){fmt.Fprintf(w,"Hello, World!")})// 启动服务器,监听 8080 端口fmt.Println("服务器启动在 http://localhost:8080")http.ListenAndServe(":8080",nil)}运行程序:
go run main.go测试:
curlhttp://localhost:8080# 输出: Hello, World!1.2 HTTP 服务器核心组件
核心类型:
http.Server:HTTP 服务器http.Handler:请求处理接口http.ResponseWriter:响应写入器http.Request:请求对象
二、理解 Handler 和 HandlerFunc
2.1 Handler 接口
typeHandlerinterface{ServeHTTP(ResponseWriter,*Request)}2.2 使用 HandlerFunc
packagemainimport("fmt""net/http")// 方式一:使用函数funchomeHandler(w http.ResponseWriter,r*http.Request){fmt.Fprintf(w,"欢迎来到首页!")}// 方式二:使用 HandlerFuncvaraboutHandler=http.HandlerFunc(func(w http.ResponseWriter,r*http.Request){fmt.Fprintf(w,"关于我们")})funcmain(){http.HandleFunc("/",homeHandler)http.Handle("/about",aboutHandler)http.ListenAndServe(":8080",nil)}2.3 自定义 Handler
packagemainimport("fmt""net/http")typeMyHandlerstruct{Messagestring}func(h*MyHandler)ServeHTTP(w http.ResponseWriter,r*http.Request){fmt.Fprintf(w,"消息: %s",h.Message)}funcmain(){handler:=&MyHandler{Message:"Hello from custom handler!"}http.Handle("/custom",handler)http.ListenAndServe(":8080",nil)}三、处理不同的 HTTP 方法
3.1 区分 GET 和 POST
packagemainimport("fmt""net/http")funcuserHandler(w http.ResponseWriter,r*http.Request){switchr.Method{casehttp.MethodGet:// 处理 GET 请求fmt.Fprintf(w,"获取用户信息")casehttp.MethodPost:// 处理 POST 请求fmt.Fprintf(w,"创建用户")casehttp.MethodPut