Go 网络编程:HTTP服务与客户端开发

Go 在标准库中内置了功能强大的 net/http 包,可快速构建高并发、高性能的 HTTP 服务,广泛应用于微服务、Web后端、API中间层等场景。


一、快速创建一个HTTP服务

示例:最简Hello服务

go 复制代码
package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, Go Web!")
}

func main() {
    http.HandleFunc("/", helloHandler)
    fmt.Println("Listening on http://localhost:8080/")
    http.ListenAndServe(":8080", nil)
}

二、请求与响应对象详解

  • http.Request:封装了客户端请求的所有信息(URL、Header、Body等)
  • http.ResponseWriter:用于构造服务器的响应

示例:获取请求信息

swift 复制代码
func infoHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Method: %s\n", r.Method)
    fmt.Fprintf(w, "URL: %s\n", r.URL.Path)
    fmt.Fprintf(w, "Header: %v\n", r.Header)
}

三、处理URL参数与POST数据

1. 获取查询参数

scss 复制代码
func queryHandler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("name")
    fmt.Fprintf(w, "Hello, %s!", name)
}

访问:http://localhost:8080/query?name=Go

2. 处理表单数据(POST)

scss 复制代码
func formHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    username := r.FormValue("username")
    fmt.Fprintf(w, "Welcome, %s!", username)
}

四、自定义HTTP路由与Handler

使用 http.ServeMux

css 复制代码
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/hello", helloHandler)
    mux.HandleFunc("/info", infoHandler)
    http.ListenAndServe(":8080", mux)
}

使用第三方路由器(如 gorilla/muxchi 等)

arduino 复制代码
// 示例略,可根据需要引入第三方库

五、构建HTTP客户端请求

Go 提供了强大的 http.Client 支持 GET/POST 等请求。

示例:GET请求

css 复制代码
resp, err := http.Get("https://httpbin.org/get")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))

示例:POST请求

go 复制代码
data := url.Values{"name": {"Go"}}
resp, err := http.PostForm("https://httpbin.org/post", data)
defer resp.Body.Close()

六、JSON接口的处理

JSON响应

go 复制代码
func jsonHandler(w http.ResponseWriter, r *http.Request) {
    type Resp struct {
        Status string `json:"status"`
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(Resp{"ok"})
}

JSON请求解析

go 复制代码
func receiveJSON(w http.ResponseWriter, r *http.Request) {
    type Req struct {
        Name string `json:"name"`
    }
    var data Req
    json.NewDecoder(r.Body).Decode(&data)
    fmt.Fprintf(w, "Hello, %s", data.Name)
}

七、静态文件服务

less 复制代码
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("public"))))

访问 /static/index.html 实际读取 public/index.html 文件。


八、HTTP中间件的编写

中间件常用于实现日志、认证、限流等功能。

go 复制代码
func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("Request: %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

九、启动HTTPS服务(SSL)

go 复制代码
http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)

用于生产环境时,请使用自动证书工具如 Let's Encrypt + Caddy/Nginx 做代理。


十、总结

能力 工具与API
启动Web服务 http.ListenAndServe
构造REST接口 HandlerFunc + JSON 编解码
发起HTTP请求 http.Get, http.Post, http.Client
路由与中间件 ServeMux 或第三方路由器
文件服务与HTTPS http.FileServer / ListenAndServeTLS
相关推荐
烂蜻蜓9 小时前
Flask入门教程(二十六):Session API——用户会话状态管理
后端·python·flask
郑州光合科技余经理11 小时前
本地生活服务系统:成品模块和定制接口怎么划界
java·前端·人工智能·后端·系统架构·php·ai编程
朦胧之16 小时前
PostgreSQL 数据库笔记
人工智能·后端
IT_陈寒19 小时前
Redis缓存雪崩把我坑惨了,这次长记性了
前端·人工智能·后端
LucianaiB19 小时前
用 WorkBuddy 研究腾讯、阿里和 DeepSeek,我没敢直接说「AI 很赚钱」
后端
Vespeng19 小时前
打破传统 MVC:在 Go 中实践高内聚的业务驱动架构
架构·go·gin
用户83562907805119 小时前
使用 Python 管理 PDF 属性和元数据
后端·python
分支预测失败19 小时前
RISC-V 上下文切换实战:从 Trap 入口到 Linux 进程调度
后端·嵌入式
用户83562907805120 小时前
使用 Python 在 Word 文档中创建自定义图表
后端·python
Profile排查笔记20 小时前
JavaScript 实现浏览器指纹生成:基础字段、Canvas 采样与 SHA-256 摘要
前端·人工智能·后端·自动化