1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 07:20:55 +00:00

refactored the building of healthcheck response map

This commit is contained in:
Eyitayo Ogunbiyi 2020-07-07 16:09:22 +01:00
parent ca0c64b69e
commit 469dc7bea9

View File

@ -21,6 +21,7 @@ import (
"net/http" "net/http"
"os" "os"
"reflect" "reflect"
"strconv"
"text/template" "text/template"
"time" "time"
@ -321,28 +322,18 @@ func healthcheck(rw http.ResponseWriter, r *http.Request) {
} }
queryParams := r.URL.Query() queryParams := r.URL.Query()
jsonFlag := queryParams.Get("json")
shouldReturnJSON, _ := strconv.ParseBool(jsonFlag)
if queryParams["json"] != nil { if shouldReturnJSON {
responseMap := buildHealthCheckResponseMap(resultList)
jsonResponse, err := json.Marshal(responseMap)
type Result map[string]interface{}
response := make([]Result, len(*resultList))
for i, currentResult := range *resultList {
currentResultMap := make(Result)
currentResultMap["name"] = currentResult[0]
currentResultMap["message"] = currentResult[1]
currentResultMap["status"] = currentResult[2]
response[i] = currentResultMap
}
JSONResponse, err := json.Marshal(response)
if err != nil { if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError) http.Error(rw, err.Error(), http.StatusInternalServerError)
} else { } else {
writeJSON(rw, JSONResponse) writeJSON(rw, jsonResponse)
} }
return return
} }
@ -353,6 +344,23 @@ func healthcheck(rw http.ResponseWriter, r *http.Request) {
writeTemplate(rw, data, healthCheckTpl, defaultScriptsTpl) writeTemplate(rw, data, healthCheckTpl, defaultScriptsTpl)
} }
func buildHealthCheckResponseMap(resultList *[][]string) []map[string]interface{} {
response := make([]map[string]interface{}, len(*resultList))
for i, currentResult := range *resultList {
currentResultMap := make(map[string]interface{})
currentResultMap["name"] = currentResult[0]
currentResultMap["message"] = currentResult[1]
currentResultMap["status"] = currentResult[2]
response[i] = currentResultMap
}
return response
}
func writeJSON(rw http.ResponseWriter, jsonData []byte) { func writeJSON(rw http.ResponseWriter, jsonData []byte) {
rw.Header().Set("Content-Type", "application/json") rw.Header().Set("Content-Type", "application/json")
rw.Write(jsonData) rw.Write(jsonData)