鲜嫩多汁的味蕾探险:当丘丘人遇上甘雨,一场意想不到的“白灼”风味革命

核心内容摘要

xrk站长统计:数据驱动的增长引擎,MBA智库的智慧增长秘诀
4438x:当极致遇上无限可能,全国最大想象力版图由此开启_1

桥本有菜T2U摄影集定格极致诱惑,解锁无限遐想_2

12 Go HTTP服务器进阶:路由、中间件、错误处理完整实现引言构建生产级的HTTP服务器需要路由管理、中间件机制和统一的错误处理。

本文将深入讲解这些进阶功能,帮助你构建健壮的HTTP服务器。

路由管理

1 自定义路由器packagemainimport("fmt""net/http")typeRouterstruct{routesmap[string]http.HandlerFunc}funcNewRouter()*Router{returnRouter{routes:make(map[string]http.HandlerFunc),}}func(r*Router)HandleFunc(patternstring,handler http.HandlerFunc){r.routes[pattern]=handler}func(r*Router)ServeHTTP(w http.ResponseWriter,req*http.Request){handler,ok:=r.routes[req.URL.Path]if!ok{http.NotFound(w,req)return}handler(w,req)}funcmain(){router:=NewRouter()router.HandleFunc("/",func(w http.ResponseWriter,r*http.Request){fmt.Fprintf(w,"首页")})router.HandleFunc("/about",func(w http.ResponseWriter,r*http.Request){fmt.Fprintf(w,"关于")})http.ListenAndServe(":8080",router)}

2 使用Gorilla Muxpackagemainimport("fmt""net/http""github.com/gorilla/mux")funcmain(){r:=mux.NewRouter()// 精确匹配r.HandleFunc("/users",listUsers).Methods("GET")r.HandleFunc("/users",createUser).Methods("POST")// 路径参数r.HandleFunc("/users/{id:[

]+}",getUser).Methods("GET")r.HandleFunc("/users/{id:[

]+}",updateUser).Methods("PUT")r.HandleFunc("/users/{id:[

]+}",deleteUser).Methods("DELETE")// 子路由api:=r.PathPrefix("/api/v1").Subrouter()api.HandleFunc("/users",apiListUsers).Methods("GET")http.ListenAndServe(":8080",r)}

中间件机制

1 中间件基础packagemainimport("fmt""log""net/http""time")typeMiddlewarefunc(http.HandlerFunc)http.HandlerFuncfuncLoggingMiddleware(next http.HandlerFunc)http.HandlerFunc{returnfunc(w http.ResponseWriter,r*http.Request){start:=time.Now()log.Printf("开始 %s %s",r.Method,r.URL.Path)next(w,r)log.Printf("完成 %s %s (耗时: %v)",r.Method,r.URL.Path,time.Since(start))}}funcAuthMiddleware(next http.HandlerFunc)http.HandlerFunc{returnfunc(w http.ResponseWriter,r*http.Request){token:=r.Header.Get("Authorization")iftoken==""

男生女生一起愁愁愁素材动漫-男生女生一起愁愁愁素材动漫应用

百度百家号客服电话人工服务

123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123