github.com/splucs/witchcraft-go-server@v1.7.0/status/routes/routes.go (about)

     1  // Copyright (c) 2018 Palantir Technologies. All rights reserved.
     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 routes
    16  
    17  import (
    18  	"net/http"
    19  
    20  	"github.com/palantir/witchcraft-go-server/rest"
    21  	"github.com/palantir/witchcraft-go-server/status"
    22  	"github.com/palantir/witchcraft-go-server/witchcraft/refreshable"
    23  	"github.com/palantir/witchcraft-go-server/witchcraft/wresource"
    24  )
    25  
    26  func AddLivenessRoutes(resource wresource.Resource, source status.Source) error {
    27  	return resource.Get("liveness", status.LivenessEndpoint, handler(source))
    28  }
    29  
    30  func AddReadinessRoutes(resource wresource.Resource, source status.Source) error {
    31  	return resource.Get("readiness", status.ReadinessEndpoint, handler(source))
    32  }
    33  
    34  func AddHealthRoutes(resource wresource.Resource, source status.HealthCheckSource, sharedSecret refreshable.String) error {
    35  	return resource.Get("health", status.HealthEndpoint, status.NewHealthCheckHandler(source, sharedSecret))
    36  }
    37  
    38  // handler returns an HTTP handler that writes a response based on the provided source. The status code of the response
    39  // is determined based on the status reported by the source and the status metadata returned by the source is written as
    40  // JSON in the response body.
    41  func handler(source status.Source) http.Handler {
    42  	return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
    43  		respCode, metadata := source.Status()
    44  
    45  		// if metadata is nil, create an empty json object instead of returning 'null' which http-remoting rejects.
    46  		if metadata == nil {
    47  			metadata = struct{}{}
    48  		}
    49  
    50  		rest.WriteJSONResponse(w, metadata, respCode)
    51  	})
    52  }