Live video on the AT Protocol
1package api
2
3import (
4 "context"
5 "fmt"
6 "net/http"
7 "path/filepath"
8
9 "github.com/caddyserver/certmagic"
10 "stream.place/streamplace/pkg/log"
11)
12
13// getCertMagicStorage returns a configured storage instance for CertMagic
14func (a *StreamplaceAPI) getCertMagicStorage() *StreamplaceCertStorage {
15 storagePath := filepath.Join(a.CLI.DataDir, "certmagic")
16 return NewStreamplaceCertStorage(storagePath)
17}
18
19// serve with CertMagic
20func (a *StreamplaceAPI) ServeHTTPSWithCertMagic(ctx context.Context) error {
21 if a.CLI.PublicHost == "" {
22 return fmt.Errorf("public-host must be set when using CertMagic")
23 }
24
25 // Configure custom storage
26 storage := a.getCertMagicStorage()
27 certmagic.Default.Storage = storage
28
29 // Configure ACME settings
30 if a.CLI.CertMagicCAURL != "" {
31 certmagic.DefaultACME.CA = a.CLI.CertMagicCAURL
32 }
33 certmagic.DefaultACME.Agreed = true
34
35 handler, err := a.Handler(ctx)
36 if err != nil {
37 return err
38 }
39
40 return a.ServerWithShutdown(ctx, handler, func(s *http.Server) error {
41 s.Addr = a.CLI.HTTPSAddr
42
43 tlsConfig := certmagic.Default.TLSConfig()
44 tlsConfig.NextProtos = append([]string{"h2", "http/1.1"}, tlsConfig.NextProtos...)
45 s.TLSConfig = tlsConfig
46
47 log.Log(ctx, "https server starting with CertMagic",
48 "addr", s.Addr,
49 "domain", a.CLI.PublicHost,
50 "ca", certmagic.DefaultACME.CA,
51 "storage_path", storage.Path,
52 )
53
54 err := certmagic.ManageAsync(ctx, []string{a.CLI.PublicHost})
55 if err != nil {
56 return fmt.Errorf("failed to start certificate management: %w", err)
57 }
58
59 return s.ListenAndServeTLS("", "")
60 })
61}