Golang 标准库 - 示例代码

net/http

Golang 标准库 - net/http

net/http 提供 HTTP 客户端与服务端的完整实现,支持 HTTP/1.1 与 HTTP/2。一个 ListenAndServe 就能起一个生产级 HTTP 服务,是 Go 最常用的标准库之一。

核心能力速查

能力 入口 说明
简单请求 http.Get() / http.Post() 快速发起请求
自定义请求 http.NewRequest() + Client.Do() 可设 Header、超时
带超时客户端 &http.Client{Timeout: d} 生产必加超时
注册路由 http.HandleFunc() 注册处理函数
启动服务 http.ListenAndServe() 监听端口
多路复用器 http.ServeMux 路由分发
处理接口 http.Handler 中间件的基石

可运行示例:客户端 + 服务端 + 中间件

package main

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

func main() {
	// 1. HTTP 客户端:带超时 + 自定义 Header
	client := &http.Client{Timeout: 10 * time.Second}
	req, _ := http.NewRequest("GET", "https://api.github.com", nil)
	req.Header.Set("Accept", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	fmt.Printf("Status: %s, Length: %d\n", resp.Status, len(body))

	// 2. HTTP 服务端:路由 + 中间件
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, Method: %s\n", r.Method)
	})
	mux.HandleFunc("/user/", func(w http.ResponseWriter, r *http.Request) {
		name := r.URL.Path[len("/user/"):]
		fmt.Fprintf(w, "Hello, %s!\n", name)
	})

	// 中间件:记录每个请求耗时
	handler := logging(mux)

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

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

站内深度阅读(原理篇)

会用 ListenAndServe 只是第一步,真正理解 Go HTTP 的并发模型才能扛住面试和线上压力:

相关阅读

🛒 站长推荐(京东联盟)

以上链接含京东联盟推广代码;通过链接购买本站可能获得少量佣金,不影响你的购买价格。

📮 关注公众号「Go2AI之路」
Go2AI之路 公众号二维码

每周更新 Go + AI 应用开发实战:AI 面试官完整项目、MCP、Agent 工程化,完整源码随文章首发。

微信扫码,或搜索「Go2AI之路」关注,第一时间获取系列更新与源码,不再错过任何一篇。

如有疑问关注公众号给我留言
wx

关注公众号

©2017-2026 鲁ICP备17023316号-1 Powered by Hugo · 隐私政策