whatismyip/server/quic.go

56 lines
1.2 KiB
Go
Raw Permalink Normal View History

2023-03-20 15:33:45 +00:00
package server
import (
"context"
2024-03-23 16:41:34 +00:00
"errors"
2023-03-20 15:33:45 +00:00
"log"
"net/http"
"github.com/dcarrillo/whatismyip/internal/setting"
"github.com/quic-go/quic-go/http3"
)
2024-03-23 16:41:34 +00:00
type Quic struct {
2023-03-20 15:33:45 +00:00
server *http3.Server
2024-03-23 16:41:34 +00:00
tlsServer *TLS
2023-03-20 15:33:45 +00:00
ctx context.Context
}
2024-03-23 16:41:34 +00:00
func NewQuicServer(ctx context.Context, tlsServer *TLS) *Quic {
return &Quic{
2023-03-20 15:33:45 +00:00
tlsServer: tlsServer,
ctx: ctx,
}
}
2024-03-23 16:41:34 +00:00
func (q *Quic) Start() {
2023-03-20 15:33:45 +00:00
q.server = &http3.Server{
Addr: setting.App.TLSAddress,
Handler: q.tlsServer.server.Handler,
}
parentHandler := q.tlsServer.server.Handler
q.tlsServer.server.Handler = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if err := q.server.SetQuicHeaders(rw.Header()); err != nil {
log.Fatal(err)
}
parentHandler.ServeHTTP(rw, req)
})
log.Printf("Starting QUIC server listening on %s (udp)", setting.App.TLSAddress)
go func() {
if err := q.server.ListenAndServeTLS(setting.App.TLSCrtPath, setting.App.TLSKeyPath); err != nil &&
2024-03-23 16:41:34 +00:00
!errors.Is(err, http.ErrServerClosed) {
2023-03-20 15:33:45 +00:00
log.Fatal(err)
}
}()
}
2024-03-23 16:41:34 +00:00
func (q *Quic) Stop() {
log.Printf("Stopping QUIC server...")
2023-03-20 15:33:45 +00:00
if err := q.server.Close(); err != nil {
log.Printf("QUIC server forced to shutdown")
}
}