/* * Copyright (C) 2021 Orange & contributors * * This program is free software; you can redistribute it and/or modify it under the terms * * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth * Floor, Boston, MA 02110-1301, USA. */ package internal import ( "encoding/json" "fmt" "log" "net/http" "strings" "time" ) type healthResponse struct { Status string `json:"status"` } const readHeaderTimeout = 2 * time.Second func serverHandler(writer http.ResponseWriter, request *http.Request) { if strings.ToUpper(request.Method) != "GET" { http.Error(writer, "Method not allowed", http.StatusMethodNotAllowed) } else if request.URL.Path != "/health" { http.Error(writer, fmt.Sprintf("Not found: %s", request.RequestURI), http.StatusNotFound) } else { health(writer, request) } } func health(writer http.ResponseWriter, request *http.Request) { body, err := json.Marshal(healthResponse{Status: "OK"}) if err != nil { http.Error(writer, err.Error(), http.StatusInternalServerError) return } writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(http.StatusOK) if _, err = writer.Write(body); err != nil { panic("Error while sending response in health") } } func HealthService(port int) (error, *http.Server) { log.Printf("Starting application on port %d\n", port) server := &http.Server{ Addr: fmt.Sprintf(":%d", port), Handler: http.HandlerFunc(serverHandler), ReadHeaderTimeout: readHeaderTimeout, } return server.ListenAndServe(), server }