內容不多,只有部分筆記,剩下的沒有繼續學下去,包括路由與處理器、日志中間件、請求上下文
文章目錄
- 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(遠程過程調用)、服務治理、持久化層(數據層)、配置與日志、定時任務、監控與報警、微服務架構支持