-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
68 lines (60 loc) · 1.29 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"errors"
"fmt"
"log"
"net"
"os"
"github.com/defval/di"
)
// Configuration
type Configuration struct {
ConnectionType string
}
// NewConfiguration creates new configuration.
func NewConfiguration() *Configuration {
c := &Configuration{
ConnectionType: "tcp",
}
if typ, ok := os.LookupEnv("CONNECTION_TYPE"); ok {
c.ConnectionType = typ
}
return c
}
// NewTCPConnection creates tcp connection
func NewTCPConn() *net.TCPConn {
return &net.TCPConn{}
}
// NewUDPConn creates udp connection
func NewUDPConn() *net.UDPConn {
return &net.UDPConn{}
}
// ProvideConfiguredConnection
func ProvideConfiguredConnection(conf *Configuration, container *di.Container) error {
switch conf.ConnectionType {
case "tcp":
return container.Provide(NewTCPConn, di.As(new(net.Conn)))
case "udp":
return container.Provide(NewUDPConn, di.As(new(net.Conn)))
}
return errors.New("unknown connection type")
}
func main() {
c, err := di.New(
di.Provide(NewConfiguration),
di.Invoke(ProvideConfiguredConnection),
)
if err != nil {
log.Fatalln(err)
}
var conn net.Conn
if err := c.Resolve(&conn); err != nil {
log.Fatalln(err)
}
switch conn.(type) {
case *net.TCPConn:
fmt.Println("Provided connection: TCP")
case *net.UDPConn:
fmt.Println("Provided connection: UDP")
}
}