()
| 182 | } |
| 183 | |
| 184 | func Example() { |
| 185 | app := fx.New( |
| 186 | // Provide all the constructors we need, which teaches Fx how we'd like to |
| 187 | // construct the *log.Logger, http.Handler, and *http.ServeMux types. |
| 188 | // Remember that constructors are called lazily, so this block doesn't do |
| 189 | // much on its own. |
| 190 | fx.Provide( |
| 191 | NewLogger, |
| 192 | NewHandler, |
| 193 | NewMux, |
| 194 | ), |
| 195 | // Since constructors are called lazily, we need some invocations to |
| 196 | // kick-start our application. In this case, we'll use Register. Since it |
| 197 | // depends on an http.Handler and *http.ServeMux, calling it requires Fx |
| 198 | // to build those types using the constructors above. Since we call |
| 199 | // NewMux, we also register Lifecycle hooks to start and stop an HTTP |
| 200 | // server. |
| 201 | fx.Invoke(Register), |
| 202 | |
| 203 | // This is optional. With this, you can control where Fx logs |
| 204 | // its events. In this case, we're using a NopLogger to keep |
| 205 | // our test silent. Normally, you'll want to use an |
| 206 | // fxevent.ZapLogger or an fxevent.ConsoleLogger. |
| 207 | fx.WithLogger( |
| 208 | func() fxevent.Logger { |
| 209 | return fxevent.NopLogger |
| 210 | }, |
| 211 | ), |
| 212 | ) |
| 213 | |
| 214 | // In a typical application, we could just use app.Run() here. Since we |
| 215 | // don't want this example to run forever, we'll use the more-explicit Start |
| 216 | // and Stop. |
| 217 | startCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| 218 | defer cancel() |
| 219 | if err := app.Start(startCtx); err != nil { |
| 220 | log.Fatal(err) |
| 221 | } |
| 222 | |
| 223 | // Normally, we'd block here with <-app.Done(). Instead, we'll make an HTTP |
| 224 | // request to demonstrate that our server is running. |
| 225 | if _, err := http.Get("http://localhost:8080/"); err != nil { |
| 226 | log.Fatal(err) |
| 227 | } |
| 228 | |
| 229 | stopCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| 230 | defer cancel() |
| 231 | if err := app.Stop(stopCtx); err != nil { |
| 232 | log.Fatal(err) |
| 233 | } |
| 234 | |
| 235 | // Output: |
| 236 | // Executing NewLogger. |
| 237 | // Executing NewMux. |
| 238 | // Executing NewHandler. |
| 239 | // Starting HTTP server. |
| 240 | // Got a request. |
| 241 | // Stopping HTTP server. |
nothing calls this directly
no test coverage detected