...

Source file src/sigs.k8s.io/controller-runtime/pkg/certwatcher/example_test.go

Documentation: sigs.k8s.io/controller-runtime/pkg/certwatcher

     1  /*
     2  Copyright 2018 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package certwatcher_test
    18  
    19  import (
    20  	"context"
    21  	"crypto/tls"
    22  	"net/http"
    23  	"time"
    24  
    25  	ctrl "sigs.k8s.io/controller-runtime"
    26  	"sigs.k8s.io/controller-runtime/pkg/certwatcher"
    27  )
    28  
    29  type sampleServer struct {
    30  }
    31  
    32  func Example() {
    33  	// Setup Context
    34  	ctx := ctrl.SetupSignalHandler()
    35  
    36  	// Initialize a new cert watcher with cert/key pair
    37  	watcher, err := certwatcher.New("ssl/tls.crt", "ssl/tls.key")
    38  	if err != nil {
    39  		panic(err)
    40  	}
    41  
    42  	// Start goroutine with certwatcher running fsnotify against supplied certdir
    43  	go func() {
    44  		if err := watcher.Start(ctx); err != nil {
    45  			panic(err)
    46  		}
    47  	}()
    48  
    49  	// Setup TLS listener using GetCertficate for fetching the cert when changes
    50  	listener, err := tls.Listen("tcp", "localhost:9443", &tls.Config{
    51  		GetCertificate: watcher.GetCertificate,
    52  		MinVersion:     tls.VersionTLS12,
    53  	})
    54  	if err != nil {
    55  		panic(err)
    56  	}
    57  
    58  	// Initialize your tls server
    59  	srv := &http.Server{
    60  		Handler:           &sampleServer{},
    61  		ReadHeaderTimeout: 5 * time.Second,
    62  	}
    63  
    64  	// Start goroutine for handling server shutdown.
    65  	go func() {
    66  		<-ctx.Done()
    67  		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    68  		defer cancel()
    69  		if err := srv.Shutdown(ctx); err != nil {
    70  			panic(err)
    71  		}
    72  	}()
    73  
    74  	// Serve t
    75  	if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
    76  		panic(err)
    77  	}
    78  }
    79  
    80  func (s *sampleServer) ServeHTTP(http.ResponseWriter, *http.Request) {
    81  }
    82  

View as plain text