From 31883b10bf897b01946e6537a9f4f2c88aaa3bea Mon Sep 17 00:00:00 2001
From: Aksel Baardsen <akselba@stud.ntnu.no>
Date: Sat, 19 Oct 2019 15:39:01 +0200
Subject: [PATCH] added status codes as strings diag

---
 pkg/diag.go | 27 ++++++++++++++++++++-------
 1 file changed, 20 insertions(+), 7 deletions(-)

diff --git a/pkg/diag.go b/pkg/diag.go
index 8599661..8771428 100644
--- a/pkg/diag.go
+++ b/pkg/diag.go
@@ -1,7 +1,8 @@
 package pkg
 
 import (
-	"fmt"
+	"strconv"
+	"strings"
 	"time"
 )
 
@@ -16,8 +17,8 @@ func init() {
 
 // struct for returning requested data
 type Diag struct {
-	Gbif          int    	`json:"gbif,omitempty"`
-	Restcountries int    	`json:"restcountries,omitempty"`
+	Gbif          string    `json:"gbif,omitempty"`
+	Restcountries string    `json:"restcountries,omitempty"`
 	Version       string 	`json:"version,omitempty"`
 	Uptime        int 		`json:"uptime,omitempty"`
 }
@@ -27,12 +28,22 @@ func GetDiag(d* Diag) error {
 
 	// gets status of GBIF api, returns appropriate error
 	if err := getGbifStatus(d); err != nil{
-		return fmt.Errorf("error occured while contacting GBIF API: %s", err)
+		// if it was a timeout caused by the http.client
+		if strings.Contains(err.Error(), "error occured while contacting") {
+			d.Gbif = "503: Request timed out"
+		} else {
+			return err
+		}
 	}
 
 	// gets status of restcountries api, returns appropriate error
 	if err := getRestStatus(d); err != nil {
-		return fmt.Errorf("error occured while contacting Restcountries API: %s", err)
+		// if it was a timeout caused by the http.client
+		if strings.Contains(err.Error(), "error occured while contacting") {
+			d.Gbif = "503: Request timed out"
+		} else {
+			return err
+		}
 	}
 
 	d.Version = "v1"
@@ -48,7 +59,8 @@ func getGbifStatus(d *Diag) error {
 	if err != nil {
 		return err
 	}
-	d.Gbif = resp.StatusCode
+	defer resp.Body.Close()
+	d.Gbif = strconv.Itoa(resp.StatusCode)
 	return nil
 }
 
@@ -58,7 +70,8 @@ func getRestStatus(d *Diag) error {
 	if err != nil {
 		return err
 	}
-	d.Restcountries = resp.StatusCode
+	defer resp.Body.Close()
+	d.Restcountries = strconv.Itoa(resp.StatusCode)
 	return nil
 }
 
-- 
GitLab