-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
98 lines (86 loc) · 2.4 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright (c) 2023 Z5Labs and Contributors
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package main
import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"log/slog"
"math/big"
"net/http"
"os"
"time"
"github.com/z5labs/bedrock"
brhttp "github.com/z5labs/bedrock/http"
"github.com/z5labs/bedrock/pkg/lifecycle"
"github.com/z5labs/bedrock/pkg/otelconfig"
)
func createCert() (tls.Certificate, error) {
_, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return tls.Certificate{}, err
}
// ECDSA, ED25519 and RSA subject keys should have the DigitalSignature
// KeyUsage bits set in the x509.Certificate template
notBefore := time.Now()
notAfter := notBefore.Add(365 * 24 * time.Hour)
template := x509.Certificate{
SerialNumber: big.NewInt(time.Now().Unix()),
Subject: pkix.Name{
Organization: []string{"Acme Co"},
},
NotBefore: notBefore,
NotAfter: notAfter,
SubjectKeyId: []byte{113, 117, 105, 99, 107, 115, 101, 114, 118, 101},
BasicConstraintsValid: true,
IsCA: true,
KeyUsage: x509.KeyUsageKeyEncipherment |
x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, priv.Public().(ed25519.PublicKey), priv)
if err != nil {
return tls.Certificate{}, nil
}
var cert tls.Certificate
cert.Certificate = append(cert.Certificate, derBytes)
cert.PrivateKey = priv
return cert, nil
}
func initRuntime(ctx context.Context) (bedrock.Runtime, error) {
logHandler := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{AddSource: true})
cert, err := createCert()
if err != nil {
return nil, err
}
rt := brhttp.NewRuntime(
brhttp.ListenOnPort(8080),
brhttp.LogHandler(logHandler),
brhttp.TLSConfig(&tls.Config{
Certificates: []tls.Certificate{cert},
}),
brhttp.Http2Only(),
brhttp.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello, world")
}),
)
return rt, nil
}
func localOtel(ctx context.Context) (otelconfig.Initializer, error) {
initer := otelconfig.Local()
return initer, nil
}
func main() {
bedrock.New(
bedrock.Hooks(
lifecycle.ManageOTel(localOtel),
),
bedrock.WithRuntimeBuilderFunc(initRuntime),
).Run()
}