🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 概述 ``` package main import ( "context" "fmt" "go.uber.org/fx" "io" "net" "net/http" "os" ) func NewHTTPServer(lc fx.Lifecycle, mux *http.ServeMux) *http.Server { srv := &http.Server{Addr: ":8080", Handler: mux} lc.Append(fx.Hook{ OnStart: func(ctx context.Context) error { ln, err := net.Listen("tcp", srv.Addr) if err != nil { return err } fmt.Println("Starting HTTP server at", srv.Addr) go srv.Serve(ln) return nil }, OnStop: func(ctx context.Context) error { return srv.Shutdown(ctx) }, }) return srv } type EchoHandler struct{} // NewEchoHandler builds a new EchoHandler. func NewEchoHandler() *EchoHandler { return &EchoHandler{} } // ServeHTTP handles an HTTP request to the /echo endpoint. func (*EchoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if _, err := io.Copy(w, r.Body); err != nil { fmt.Fprintln(os.Stderr, "Failed to handle request:", err) } } func NewServeMux(echo *EchoHandler) *http.ServeMux { mux := http.NewServeMux() mux.Handle("/echo", echo) return mux } func main() { fx.New( // 没有先后顺序 fx.Provide( NewHTTPServer, NewEchoHandler, NewServeMux, ), fx.Invoke(func(*http.Server) {}), ).Run() } ```