Browse Source

Add more abstraction

Rufus Deponian 3 years ago
parent
commit
497901da74
1 changed files with 15 additions and 25 deletions
  1. 15 25
      sdApi1/sdApi1.go

+ 15 - 25
sdApi1/sdApi1.go

@@ -17,37 +17,23 @@ func SetApiKey(newApiKey string) {
 	apiKey = newApiKey
 }
 
-func GetUnits() (models.Units, error) {
-	var units models.Units
-	buf, err := getJSON("https://sd.mephi.ru/api/1/units.json")
+func GetUnits() (units models.Units, err error) {
+	err = getItems(&units, "https://sd.mephi.ru/api/1/units.json")
 	if err != nil {
-		return nil, err
-	}
-
-	if err := json.Unmarshal(buf.Bytes(), &units); err != nil {
-		return nil, fmt.Errorf("Cannot parse: %v: \"%v\"", string(buf.Bytes()), err.Error())
+		return
 	}
 
 	units.CalculateTree()
 
-	return units, nil
+	return
 }
 
-func GetPeople() (models.People, error) {
-	var people models.People
-	buf, err := getJSON("https://sd.mephi.ru/api/1/faces.json")
-	if err != nil {
-		return nil, err
-	}
-
-	if err := json.Unmarshal(buf.Bytes(), &people); err != nil {
-		return nil, fmt.Errorf("Cannot parse: %v: \"%v\"", string(buf.Bytes()), err.Error())
-	}
-
-	return people, nil
+func GetPeople() (people models.People, err error) {
+	err = getItems(&people, "https://sd.mephi.ru/api/1/faces.json")
+	return
 }
 
-func getJSON(url string) (*bytes.Buffer, error) {
+func getItems(items interface{}, url string) error {
 	client := &http.Client{}
 
 	req, _ := http.NewRequest("GET", url, nil)
@@ -56,7 +42,7 @@ func getJSON(url string) (*bytes.Buffer, error) {
 	req.URL.RawQuery = q.Encode()
 	response, err := client.Do(req)
 	if err != nil {
-		return nil, err
+		return err
 	}
 	defer response.Body.Close()
 
@@ -65,8 +51,12 @@ func getJSON(url string) (*bytes.Buffer, error) {
 	buf := bytes.NewBuffer(bytesArray)
 	_, err = buf.ReadFrom(response.Body)
 	if err != nil {
-		return nil, err
+		return err
+	}
+
+	if err := json.Unmarshal(buf.Bytes(), &items); err != nil {
+		return fmt.Errorf("Cannot parse: %v: \"%v\"", string(buf.Bytes()), err.Error())
 	}
 
-	return buf, nil
+	return nil
 }