@@ -4,53 +4,58 @@ import (
4
4
"crypto/tls"
5
5
"crypto/x509"
6
6
"encoding/base64"
7
+ "errors"
7
8
"fmt"
8
9
"net/http"
9
10
"os"
10
11
)
11
12
13
+ type Server struct {
14
+ mux * http.ServeMux
15
+ tlsConfig * tls.Config
16
+ }
17
+
12
18
// CreateServer creates a new HTTP server with TLS configured for GPTScript.
13
19
// This function should be used when creating a new server for a daemon tool.
14
20
// The server should then be started with the StartServer function.
15
- func CreateServer () (* http.Server , error ) {
16
- tlsConfig , err := getTLSConfig ()
17
- if err != nil {
18
- return nil , fmt .Errorf ("failed to get TLS config: %v" , err )
19
- }
20
-
21
- server := & http.Server {
22
- Addr : fmt .Sprintf ("127.0.0.1:%s" , os .Getenv ("PORT" )),
23
- TLSConfig : tlsConfig ,
24
- }
25
- return server , nil
21
+ func CreateServer () (* Server , error ) {
22
+ return CreateServerWithMux (http .DefaultServeMux )
26
23
}
27
24
28
25
// CreateServerWithMux creates a new HTTP server with TLS configured for GPTScript.
29
26
// This function should be used when creating a new server for a daemon tool with a custom ServeMux.
30
27
// The server should then be started with the StartServer function.
31
- func CreateServerWithMux (mux * http.ServeMux ) (* http. Server , error ) {
28
+ func CreateServerWithMux (mux * http.ServeMux ) (* Server , error ) {
32
29
tlsConfig , err := getTLSConfig ()
33
30
if err != nil {
34
31
return nil , fmt .Errorf ("failed to get TLS config: %v" , err )
35
32
}
36
33
34
+ return & Server {
35
+ mux : mux ,
36
+ tlsConfig : tlsConfig ,
37
+ }, nil
38
+ }
39
+
40
+ // Start starts an HTTP server created by the CreateServer function.
41
+ // This is for use with daemon tools.
42
+ func (s * Server ) Start () error {
37
43
server := & http.Server {
38
44
Addr : fmt .Sprintf ("127.0.0.1:%s" , os .Getenv ("PORT" )),
39
- TLSConfig : tlsConfig ,
40
- Handler : mux ,
45
+ TLSConfig : s . tlsConfig ,
46
+ Handler : s . mux ,
41
47
}
42
- return server , nil
43
- }
44
48
45
- // StartServer starts an HTTP server created by the CreateServer function.
46
- // This is for use with daemon tools.
47
- func StartServer (server * http.Server ) error {
48
- if err := server .ListenAndServeTLS ("" , "" ); err != nil {
49
+ if err := server .ListenAndServeTLS ("" , "" ); err != nil && ! errors .Is (err , http .ErrServerClosed ) {
49
50
return fmt .Errorf ("stopped serving: %v" , err )
50
51
}
51
52
return nil
52
53
}
53
54
55
+ func (s * Server ) HandleFunc (pattern string , handler http.HandlerFunc ) {
56
+ s .mux .HandleFunc (pattern , handler )
57
+ }
58
+
54
59
func getTLSConfig () (* tls.Config , error ) {
55
60
certB64 := os .Getenv ("CERT" )
56
61
privateKeyB64 := os .Getenv ("PRIVATE_KEY" )
0 commit comments