From 936beb2166e05b1957ac130a7a0efd5beaa4f979 Mon Sep 17 00:00:00 2001 From: Burton Rheutan Date: Mon, 5 Mar 2018 11:35:44 -0600 Subject: [PATCH] return err from json unmarshal Signed-off-by: Burton Rheutan --- sample-functions/DockerHubStats/main.go | 28 ++++++++++++++++--------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/sample-functions/DockerHubStats/main.go b/sample-functions/DockerHubStats/main.go index f6c9fcfc..851452ca 100644 --- a/sample-functions/DockerHubStats/main.go +++ b/sample-functions/DockerHubStats/main.go @@ -38,16 +38,16 @@ func requestStats(repo string) []byte { return body } -func parseOrgStats(response []byte) dockerHubOrgStatsType { +func parseOrgStats(response []byte) (dockerHubOrgStatsType, error) { dockerHubOrgStats := dockerHubOrgStatsType{} - json.Unmarshal(response, &dockerHubOrgStats) - return dockerHubOrgStats + err := json.Unmarshal(response, &dockerHubOrgStats) + return dockerHubOrgStats, err } -func parseRepoStats(response []byte) dockerHubRepoStatsType { +func parseRepoStats(response []byte) (dockerHubRepoStatsType, error) { dockerHubRepoStats := dockerHubRepoStatsType{} - json.Unmarshal(response, &dockerHubRepoStats) - return dockerHubRepoStats + err := json.Unmarshal(response, &dockerHubRepoStats) + return dockerHubRepoStats, err } func main() { @@ -64,10 +64,18 @@ func main() { response := requestStats(request) if strings.Contains(request, "/") { - dockerHubRepoStats := parseRepoStats(response) - fmt.Printf("Repo: %s has been pulled %d times from the Docker Hub", request, dockerHubRepoStats.PullCount) + dockerHubRepoStats, err := parseRepoStats(response) + if err != nil { + log.Fatalln("Unable to parse response from Docker Hub for repository") + } else { + fmt.Printf("Repo: %s has been pulled %d times from the Docker Hub", request, dockerHubRepoStats.PullCount) + } } else { - dockerHubOrgStats := parseOrgStats(response) - fmt.Printf("The organisation or user %s has %d repositories on the Docker hub.\n", request, dockerHubOrgStats.Count) + dockerHubOrgStats, err := parseOrgStats(response) + if err != nil { + log.Fatalln("Unable to parse response from Docker Hub for user/organisation") + } else { + fmt.Printf("The organisation or user %s has %d repositories on the Docker hub.\n", request, dockerHubOrgStats.Count) + } } }