github.com/blend/go-sdk@v1.20220411.3/examples/r2/mtls/main.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package main 9 10 import ( 11 "os" 12 13 "github.com/blend/go-sdk/certutil" 14 "github.com/blend/go-sdk/graceful" 15 "github.com/blend/go-sdk/logger" 16 "github.com/blend/go-sdk/r2" 17 "github.com/blend/go-sdk/web" 18 "github.com/blend/go-sdk/webutil" 19 ) 20 21 func fatal(log logger.FatalReceiver, err error) { 22 log.Fatal(err) 23 os.Exit(1) 24 } 25 26 func main() { 27 log := logger.All() 28 29 // create the ca 30 ca, err := certutil.CreateCertificateAuthority() 31 if err != nil { 32 fatal(log, err) 33 } 34 35 caKeyPair, err := ca.GenerateKeyPair() 36 if err != nil { 37 fatal(log, err) 38 } 39 40 caPool, err := ca.CertPool() 41 if err != nil { 42 fatal(log, err) 43 } 44 45 // create the server certs 46 server, err := certutil.CreateServer("mtls-example.local", ca, certutil.OptSubjectAlternateNames("localhost")) 47 if err != nil { 48 fatal(log, err) 49 } 50 serverKeyPair, err := server.GenerateKeyPair() 51 if err != nil { 52 fatal(log, err) 53 } 54 55 client, err := certutil.CreateClient("mtls-client", ca) 56 if err != nil { 57 fatal(log, err) 58 } 59 clientKeyPair, err := client.GenerateKeyPair() 60 if err != nil { 61 fatal(log, err) 62 } 63 64 serverCertManager, err := certutil.NewCertManagerWithKeyPairs(serverKeyPair, []certutil.KeyPair{caKeyPair}, clientKeyPair) 65 if err != nil { 66 fatal(log, err) 67 } 68 69 // create a server 70 app, err := web.New( 71 web.OptLog(log), 72 web.OptBindAddr("127.0.0.1:5000"), 73 web.OptTLSConfig(serverCertManager.TLSConfig), 74 web.OptServerOptions( 75 webutil.OptHTTPServerErrorLog( 76 logger.StdlibShim(log, logger.OptShimWriterEventProvider( 77 logger.ShimWriterMessageEventProvider("http.error"), 78 )), 79 ), 80 ), 81 ) 82 if err != nil { 83 fatal(log, err) 84 } 85 86 go func() { 87 <-app.NotifyStarted() 88 89 // make some requests ... 90 log.Info("making a secure request") 91 92 if _, err := r2.New("https://localhost:5000", 93 r2.OptTLSRootCAs(caPool), 94 r2.OptTLSClientCert([]byte(clientKeyPair.Cert), []byte(clientKeyPair.Key))).Discard(); err != nil { 95 fatal(log, err) 96 } else { 97 log.Info("secure request success") 98 } 99 100 log.Info("making an insecure request") 101 if _, err := r2.New("https://localhost:5000", r2.OptTLSRootCAs(caPool)).Discard(); err != nil { 102 log.Error(err) 103 } 104 }() 105 106 if err := graceful.Shutdown(app); err != nil { 107 fatal(log, err) 108 } 109 }