diff --git a/error.go b/error.go new file mode 100644 index 0000000..6f8a753 --- /dev/null +++ b/error.go @@ -0,0 +1,22 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" +) + +type ErrorBody struct { + Error string +} + +func writeHTTPError(res http.ResponseWriter, err error) { + res.WriteHeader(400) + encodedOutput, err := json.Marshal(ErrorBody{Error: err.Error()}) + if err != nil { + fmt.Println("Failed to generate HTTP error: " + err.Error()) + } else { + res.Write(encodedOutput) + } + +} diff --git a/fail2rest.go b/fail2rest.go index 7a1139f..85d6210 100644 --- a/fail2rest.go +++ b/fail2rest.go @@ -15,10 +15,6 @@ type Configuration struct { Fail2banSocket string } -type ErrorBody struct { - Error string -} - var fail2goConn *fail2go.Conn func main() { diff --git a/global.go b/global.go index b52f767..9138dac 100644 --- a/global.go +++ b/global.go @@ -8,10 +8,17 @@ import ( ) func globalStatusHandler(res http.ResponseWriter, req *http.Request, fail2goConn *fail2go.Conn) { - globalStatus, _ := fail2goConn.GlobalStatus() + globalStatus, err := fail2goConn.GlobalStatus() - encodedOutput, err := json.Marshal(globalStatus) if err != nil { + writeHTTPError(res, err) + return + } + encodedOutput, err := json.Marshal(globalStatus) + + if err != nil { + writeHTTPError(res, err) + return } res.Write(encodedOutput)