内容不多,只有部分笔记,剩下的没有继续学下去,包括路由与处理器、日志中间件、请求上下文
文章目录
- 1、go-zero核心库
- 1.1 路由与处理器
- 1.2 日志中间件
- 1.3 请求上下文
1、go-zero核心库
1.1 路由与处理器
package mainimport ("github.com/zeromicro/go-zero/rest""net/http"
)func main() {r := rest.MustNewServer(rest.RestConf{Port: 8080, // 设置监听端口})defer r.Stop()// 定义一个处理器r.AddRoute(rest.Route{Method: http.MethodGet,Path: "/hello",Handler: helloHandler,})r.Start()
}// helloHandler 是处理 GET 请求的函数
func helloHandler(w http.ResponseWriter, r *http.Request) {w.Write([]byte("Hello, Go-zero!"))
}
1.2 日志中间件
package mainimport ("fmt""github.com/zeromicro/go-zero/rest""net/http"
)func main() {fmt.Println("http://127.0.0.1:8081/hello")r := rest.MustNewServer(rest.RestConf{Port: 8081,})defer r.Stop()// 使用中间件来记录请求日志r.Use(logMiddleware)r.AddRoute(rest.Route{Method: http.MethodGet,Path: "/hello",Handler: helloHandler,})r.Start()
}func logMiddleware(next http.HandlerFunc) http.HandlerFunc {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Printf("Received request: %s %s\n", r.Method, r.URL.Path)next.ServeHTTP(w, r)})
}// helloHandler 处理 GET 请求
func helloHandler(w http.ResponseWriter, r *http.Request) {w.Write([]byte("Hello, Go-zero!"))
}
1.3 请求上下文
package mainimport ("fmt""github.com/zeromicro/go-zero/rest""net/http"
)func main() {r := rest.MustNewServer(rest.RestConf{Port: 8080,})defer r.Stop()r.AddRoute(rest.Route{Method: http.MethodGet,Path: "/hello",Handler: helloHandler,})r.Start()
}func helloHandler(w http.ResponseWriter, r *http.Request) {user := r.Context().Value("user")if user != nil {fmt.Fprintf(w, "Hello, %s!", user)} else {fmt.Fprintf(w, "Hello, %s!", r.FormValue("name"))}}
API模式生成器、RPC(远程过程调用)、服务治理、持久化层(数据层)、配置与日志、定时任务、监控与报警、微服务架构支持