From 076807d78d7e26425229805083733cbb2f9b7693 Mon Sep 17 00:00:00 2001
From: jano3 <jano@uafrica.com>
Date: Mon, 15 Nov 2021 15:40:41 +0200
Subject: [PATCH] added a json unmarshaling function

---
 struct_utils/json.go | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
 create mode 100644 struct_utils/json.go

diff --git a/struct_utils/json.go b/struct_utils/json.go
new file mode 100644
index 0000000..ee887f5
--- /dev/null
+++ b/struct_utils/json.go
@@ -0,0 +1,20 @@
+package struct_utils
+
+import (
+	"encoding/json"
+	"fmt"
+)
+
+// UnmarshalJSON performs a JSON unmarshalling, but on type mismatches it returns a more user friendly error.
+// Used exactly the same as json.Unmarshal
+func UnmarshalJSON(data []byte, val interface{}) error {
+	err := json.Unmarshal(data, &val)
+	if err != nil {
+		typeErr, ok := err.(*json.UnmarshalTypeError)
+		if ok {
+			return fmt.Errorf("invalid type received for field '%s': expected a value of type '%s', but received type '%s'", typeErr.Field, typeErr.Type.Name(), typeErr.Value)
+		}
+	}
+
+	return err
+}
-- 
GitLab