登录
首页 >  Golang >  Go教程

Golang搭建Web服务器与请求处理教程

时间:2026-02-01 13:44:32 142浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《Golang搭建Web服务器及请求处理方法》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

最简Web服务器用http.ListenAndServe(":8080", nil)即可启动,需注意端口格式、panic处理和log.Fatal包裹;自定义ServeMux提升可维护性;参数解析需按类型调用对应方法;中间件应遵循Handler包装模式;生产环境须使用http.Server结构体配置超时、TLS等。

如何使用Golang构建Web服务器_Golang Web Server搭建与请求处理方法

net/http 启动最简 Web 服务器

Go 原生 net/http 包足够支撑生产级 HTTP 服务,不需要额外框架也能快速启动。核心是 http.ListenAndServe,它默认使用 http.DefaultServeMux 路由器。

常见错误:端口被占用、未处理 panic 导致服务静默退出、忘记加 : 前缀导致监听失败。

  • 端口必须写成 ":8080"(冒号开头),不是 "8080"
  • 监听地址为空字符串时等价于 "0.0.0.0:8080",但显式写 ":8080" 更安全
  • 建议用 log.Fatal 包裹启动逻辑,避免服务启动失败却无提示
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, Go Web!")
    })
    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

自定义 http.ServeMux 实现多路径路由

直接用 nil 作为 ListenAndServe 的第二个参数会依赖全局默认路由器,不利于模块化和测试。显式创建 http.ServeMux 是更可控的做法。

注意:http.ServeMux 不支持通配符或正则匹配,只做前缀/精确路径匹配;子路径注册顺序无关,但重复注册会 panic。

  • HandleFunc("/api/users", ...)HandleFunc("/api/users/", ...) 是两个不同路径
  • 若需 /api/users/ 自动重定向到 /api/users(或反之),得手动处理 r.URL.Path
  • 注册前可先检查是否已存在同路径 handler,避免运行时报错
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        fmt.Fprint(w, "OK")
    })
    mux.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        fmt.Fprint(w, `{"status":"success"}`)
    })

    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

读取请求参数:Query、Form、JSON 的典型处理方式

Go 不像其他语言自动解析所有入参,需按需调用方法。漏掉 r.ParseForm()r.ParseMultipartForm() 会导致 r.FormValue 返回空;对 JSON 请求忘记读取 io.ReadAll(r.Body) 也会拿不到数据。

  • r.URL.Query().Get("id") 直接读 query string,无需预解析
  • 表单提交(application/x-www-form-urlencoded)必须先调用 r.ParseForm(),再用 r.FormValue("name")
  • JSON 请求需手动读 body:body, _ := io.ReadAll(r.Body),然后 json.Unmarshal;注意 r.Body 只能读一次
  • 推荐统一用 r.Context() 传递超时、trace ID 等上下文信息,而非全局变量
package main

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

type RequestPayload struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func handlePost(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    // 处理 JSON
    if r.Header.Get("Content-Type") == "application/json" {
        var payload RequestPayload
        body, err := io.ReadAll(r.Body)
        if err != nil {
            http.Error(w, "Cannot read body", http.StatusBadRequest)
            return
        }
        if err := json.Unmarshal(body, &payload); err != nil {
            http.Error(w, "Invalid JSON", http.StatusBadRequest)
            return
        }
        fmt.Printf("Received: %+v\n", payload)
        w.WriteHeader(http.StatusOK)
        fmt.Fprint(w, "JSON received")
        return
    }

    // 处理表单
    if err := r.ParseForm(); err != nil {
        http.Error(w, "Parse form error", http.StatusBadRequest)
        return
    }
    name := r.FormValue("name")
    email := r.FormValue("email")
    fmt.Printf("Form: name=%s, email=%s\n", name, email)
    w.WriteHeader(http.StatusOK)
    fmt.Fprint(w, "Form received")
}

func main() {
    http.HandleFunc("/submit", handlePost)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

中间件模式:用函数链包装 http.Handler

Go 的中间件本质是「接收 handler、返回新 handler」的函数。标准库中 http.HandlerFunc 是类型别名,可被当作 http.Handler 使用。容易忽略的是:中间件必须显式调用 next.ServeHTTP(w, r),否则请求会终止在中间层。

典型陷阱:忘记传入 wr、在中间件里提前 write header 但后续 handler 又写 body、panic 未 recover 导致整个服务崩溃。

  • 日志中间件应在 next.ServeHTTP 前后分别记录开始与结束时间
  • 认证中间件可在调用 next 前校验 token,不通过就直接 http.Error
  • 所有中间件函数应接收 http.Handler 并返回 http.Handler,保持类型一致
package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        log.Printf("Started %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
        log.Printf("Completed %s in %v", r.URL.Path, time.Since(start))
    })
}

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        auth := r.Header.Get("Authorization")
        if auth == "" || auth != "Bearer secret123" {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        next.ServeHTTP(w, r)
    })
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Welcome to protected area!")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", homeHandler)

    // 链式包装:先 auth,再 logging
    handler := authMiddleware(loggingMiddleware(mux))

    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", handler))
}
实际部署时,http.Server 结构体本身支持超时控制、TLS 配置、连接池等关键字段,直接用 http.ListenAndServe 会丢失这些能力。上线前务必替换为显式初始化的 &http.Server{...} 实例。

到这里,我们也就讲完了《Golang搭建Web服务器与请求处理教程》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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