登录
首页 >  Golang >  Go教程

Golang搭建HTTP接口服务教程

时间:2026-01-30 18:27:51 457浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Golang搭建基础HTTP接口服务教程》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

最简HTTP服务只需两步:注册路由和启动监听;需设JSON响应头、校验请求方法、正确使用中间件、显式配置超时。

Golang实现一个基础的HTTP接口服务

net/http 启动最简 HTTP 服务

Go 原生 net/http 包足够轻量,不需要第三方框架就能跑起可用接口。核心就两步:注册路由 + 启动监听。

package main
<p>import (
"fmt"
"log"
"net/http"
)</p><p>func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Hello from Go!")
})</p><pre class="brush:php;toolbar:false;">log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))

}

注意:http.ListenAndServe 第二个参数传 nil 表示使用默认的 http.DefaultServeMux;如果传入自定义 http.ServeMuxhttp.Handler,需确保已注册对应路径。

处理 JSON 请求和响应时别漏掉 Content-Type

很多初学者返回 JSON 时只写 json.Marshal,但前端收不到数据或解析失败,大概率是没设响应头。

  • w.Header().Set("Content-Type", "application/json; charset=utf-8") 必须在 w.WriteHeader 或首次写 body 前调用
  • 手动检查 r.Method,避免 GET 接口误收 POST 数据
  • json.NewDecoder(r.Body).Decode(&v) 解析请求体,别用 ioutil.ReadAll 再反序列化(Go 1.16+ 已弃用 ioutil
func handleUser(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        w.WriteHeader(http.StatusMethodNotAllowed)
        return
    }
<pre class="brush:php;toolbar:false;">var user struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
if err := json.NewDecoder(r.Body).Decode(&amp;user); err != nil {
    w.WriteHeader(http.StatusBadRequest)
    return
}

w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})

}

加中间件要小心 http.Handler 链的执行顺序

Go 的中间件本质是函数套函数,返回新的 http.Handler。顺序错了会导致日志不打、鉴权跳过、甚至 panic。

  • 中间件包装顺序 = 执行顺序:最外层中间件最先执行,也最先收到响应
  • 必须调用 next.ServeHTTP(w, r),否则后续 handler 永远不会执行
  • 不要在中间件里提前 w.WriteHeader 或写 body,除非你明确要终止流程(如鉴权失败)
func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("Started %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r) // ← 这行不能少,也不能放错位置
        log.Printf("Completed %s %s", r.Method, r.URL.Path)
    })
}
<p>func main() {
mux := http.NewServeMux()
mux.HandleFunc("/api/data", handleData)</p><pre class="brush:php;toolbar:false;">// 中间件包裹:先日志,再 auth(假设存在)
handler := loggingMiddleware(authMiddleware(mux))
log.Fatal(http.ListenAndServe(":8080", handler))

}

生产环境必须设超时,否则连接堆积会拖垮服务

http.ListenAndServe 默认无读写超时,一个慢客户端或恶意长连接就能让整个服务不可用。

  • &http.Server{} 显式构造服务实例,控制 ReadTimeoutWriteTimeoutIdleTimeout
  • IdleTimeout 控制 keep-alive 空闲连接存活时间,建议设为 30–60 秒
  • 别依赖 context.WithTimeout 在 handler 里做超时——那是业务逻辑超时,不是连接级防护
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
    })
<pre class="brush:php;toolbar:false;">server := &amp;http.Server{
    Addr:         ":8080",
    Handler:      mux,
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout:  30 * time.Second,
}

log.Println("Server starting on :8080")
log.Fatal(server.ListenAndServe())

}

超时值不是越小越好:太短会误杀正常慢请求;但不设,服务就等于裸奔。真实部署时,这些值得结合后端依赖(DB、RPC)的 P99 延迟来定。

今天关于《Golang搭建HTTP接口服务教程》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>