Created
August 18, 2023 12:32
-
-
Save skowalak/77694dc3abec131bf38dc8632b6bc6d5 to your computer and use it in GitHub Desktop.
Using Uber's FX framework with optional dependencies in Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"go.uber.org/fx" | |
) | |
type IConfigSmall interface { | |
GetUri() string | |
} | |
type ConfigSmall struct { | |
url string | |
} | |
func (c *ConfigSmall) GetUri() string { | |
return c.url | |
} | |
type IConfigLarge interface { | |
GetUri() string | |
GetPort() string | |
} | |
type ConfigLarge struct { | |
url string | |
port string | |
} | |
func (c *ConfigLarge) GetUri() string { | |
return c.url | |
} | |
func (c *ConfigLarge) GetPort() string { | |
return c.port | |
} | |
func NewCS() IConfigSmall { | |
return &ConfigSmall{url: "https://proficloud.io"} | |
} | |
func NewCL() LargeResult { | |
cfg := &ConfigLarge{url: "https://proficloud.io/large", port: "8080"} | |
return LargeResult{ | |
ConfigSmall: cfg, | |
ConfigLarge: cfg, | |
} | |
} | |
type LargeResult struct { | |
fx.Out | |
ConfigSmall IConfigSmall | |
ConfigLarge IConfigLarge | |
} | |
type Params struct { | |
fx.In | |
ConfigSmall IConfigSmall | |
ConfigLarge IConfigLarge `optional:"true"` | |
} | |
func main() { | |
fmt.Println("Hello, 世界") | |
fx.New( | |
// Try commenting out one of the following fx.Provide statements and observe | |
//fx.Provide(NewCS), | |
fx.Provide(NewCL), | |
fx.Invoke(func(lifecycle fx.Lifecycle, p Params) { | |
fmt.Printf("parameters small: %v\n", p.ConfigSmall.GetUri()) | |
if p.ConfigLarge != nil { | |
fmt.Printf("parameters large: %v\n", p.ConfigLarge.GetPort()) | |
} else { | |
fmt.Println("fallback to default value") | |
} | |
}), | |
).Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment