github.com/elfadel/cilium@v1.6.12/pkg/health/probe/responder/responder.go (about)

     1  // Copyright 2019 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package responder
    16  
    17  // this implementation is intentionally kept with minimal dependencies
    18  // as this package typically runs in its own process
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"net/http"
    23  	"time"
    24  )
    25  
    26  // DefaultTimeout used for shutdown
    27  var DefaultTimeout = 30 * time.Second
    28  
    29  // Server wraps a minimal http server for the /hello endpoint
    30  type Server struct {
    31  	httpServer http.Server
    32  }
    33  
    34  // NewServer creates a new server listening on the given port
    35  func NewServer(port int) *Server {
    36  	return &Server{
    37  		http.Server{
    38  			Addr:    fmt.Sprintf(":%d", port),
    39  			Handler: http.HandlerFunc(serverRequests),
    40  		},
    41  	}
    42  }
    43  
    44  // Serve http requests until shut down
    45  func (s *Server) Serve() error {
    46  	return s.httpServer.ListenAndServe()
    47  }
    48  
    49  // Shutdown server gracefully
    50  func (s *Server) Shutdown() error {
    51  	ctx, cancel := context.WithTimeout(context.Background(), DefaultTimeout)
    52  	defer cancel()
    53  	return s.httpServer.Shutdown(ctx)
    54  }
    55  
    56  func serverRequests(w http.ResponseWriter, r *http.Request) {
    57  	if r.URL.Path == "/hello" {
    58  		w.WriteHeader(http.StatusOK)
    59  	} else {
    60  		w.WriteHeader(http.StatusNotFound)
    61  	}
    62  }