ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
[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() } ```