Skip to content

Commit df3ee1d

Browse files
committed
Usage example
1 parent cac5f3d commit df3ee1d

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

README.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,102 @@
77

88
The cert-source is a library designed to help with loading of TLS certificates and to streamline the process of
99
certificate rotation.
10+
11+
12+
## Usage
13+
14+
### Installation
15+
16+
```bash
17+
go get -u github.com/grepplabs/cert-source
18+
```
19+
20+
### TLS server
21+
22+
```go
23+
package main
24+
25+
import (
26+
"fmt"
27+
"log"
28+
"log/slog"
29+
"net/http"
30+
"time"
31+
32+
tlsconfig "github.com/grepplabs/cert-source/config"
33+
tlsserverconfig "github.com/grepplabs/cert-source/tls/server/config"
34+
)
35+
36+
func main() {
37+
tlsConfig, err := tlsserverconfig.GetServerTLSConfig(slog.Default(), &tlsconfig.TLSServerConfig{
38+
Enable: true,
39+
Refresh: 1 * time.Second,
40+
File: tlsconfig.TLSServerFiles{
41+
Key: "key.pem",
42+
Cert: "cert.pem",
43+
ClientCAs: "",
44+
ClientCLR: "",
45+
},
46+
})
47+
if err != nil {
48+
log.Fatalln(err)
49+
}
50+
server := &http.Server{
51+
Addr: ":8443",
52+
TLSConfig: tlsConfig,
53+
}
54+
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
55+
_, _ = fmt.Fprintf(w, "Hello, TLS world!")
56+
})
57+
err = server.ListenAndServeTLS("", "")
58+
if err != nil {
59+
log.Fatalln(err)
60+
}
61+
}
62+
```
63+
64+
### TLS Client
65+
66+
```go
67+
package main
68+
69+
import (
70+
"io"
71+
"log"
72+
"log/slog"
73+
"net/http"
74+
"time"
75+
76+
tlsconfig "github.com/grepplabs/cert-source/config"
77+
tlsclient "github.com/grepplabs/cert-source/tls/client"
78+
tlsclientconfig "github.com/grepplabs/cert-source/tls/client/config"
79+
)
80+
81+
func main() {
82+
tlsClientConfigFunc, err := tlsclientconfig.GetTLSClientConfigFunc(slog.Default(), &tlsconfig.TLSClientConfig{
83+
Enable: true,
84+
Refresh: 1 * time.Second,
85+
InsecureSkipVerify: false,
86+
File: tlsconfig.TLSClientFiles{
87+
Key: "",
88+
Cert: "",
89+
RootCAs: "ca.pem",
90+
},
91+
})
92+
if err != nil {
93+
log.Fatalln(err)
94+
}
95+
transport := tlsclient.NewDefaultRoundTripper(tlsclient.WithClientTLSConfig(tlsClientConfigFunc()))
96+
client := &http.Client{Transport: transport}
97+
resp, err := client.Get("https://localhost:8443")
98+
if err != nil {
99+
log.Fatalln(err)
100+
}
101+
defer resp.Body.Close()
102+
body, err := io.ReadAll(resp.Body)
103+
if err != nil {
104+
log.Fatalf("Failed to read response body: %v", err)
105+
}
106+
log.Printf("Server response: %s", body)
107+
}
108+
```

0 commit comments

Comments
 (0)