-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
68 lines (56 loc) · 1.69 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 (
"bufio"
"context"
"fmt"
"log"
"net"
"os"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/go-spiffe/v2/spiffetls"
"github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"
)
// serverAddress is the address that the server will listen on
const (
serverAddress = "0.0.0.0:8443"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
log.Printf("SPIFFE_ENDPOINT_SOCKET: %s", os.Getenv("SPIFFE_ENDPOINT_SOCKET"))
// Define the required SPIFFE ID of the client
clientID := spiffeid.RequireFromString("spiffe://coastal-containers.example/workload/client")
log.Printf("Starting server on %s", serverAddress)
// Create a Workload API listener for the server
listener, err := spiffetls.Listen(ctx, "tcp", serverAddress, tlsconfig.AuthorizeID(clientID))
if err != nil {
return fmt.Errorf("Error.. Unable to create TLS listener: %w", err)
}
defer listener.Close()
log.Printf("Server listening on %s", serverAddress)
for {
conn, err := listener.Accept()
if err != nil {
return fmt.Errorf("Error.. Failed to accept connection: %w", err)
}
go handleConnection(conn)
}
}
// handleConnection reads a request from the client and sends a response
func handleConnection(conn net.Conn) {
defer conn.Close()
req, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
log.Printf("Error reading incoming data: %v", err)
return
}
log.Printf("Incoming vessel says: %q", req)
// Send a response back to the client
if _, err = conn.Write([]byte("Request received SS Coastal Carrier. You are cleared to dock.\n")); err != nil {
log.Printf("Unable to send response: %v", err)
return
}
}