Browse Source

Add API 11

Rufus Deponian 3 years ago
parent
commit
5097c1fab4
1 changed files with 51 additions and 0 deletions
  1. 51 0
      sdApi11/sdApi11.go

+ 51 - 0
sdApi11/sdApi11.go

@@ -0,0 +1,51 @@
+package sdApi11
+
+import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"net/http"
+
+	models "devel.mephi.ru/dyokunev/go-sd-models/api11"
+)
+
+var (
+	apiKey string
+)
+
+func SetApiKey(newApiKey string) {
+	apiKey = newApiKey
+}
+
+func GetPeople() (people models.People, err error) {
+	err = getItems(&people, "https://sd.mephi.ru/api/11/get_people.json")
+	return
+}
+
+func getItems(items interface{}, url string) error {
+	client := &http.Client{}
+
+	req, _ := http.NewRequest("GET", url, nil)
+	q := req.URL.Query()
+	q.Add("api_key", apiKey)
+	req.URL.RawQuery = q.Encode()
+	response, err := client.Do(req)
+	if err != nil {
+		return err
+	}
+	defer response.Body.Close()
+
+	var bytesArray []byte
+
+	buf := bytes.NewBuffer(bytesArray)
+	_, err = buf.ReadFrom(response.Body)
+	if err != nil {
+		return err
+	}
+
+	if err := json.Unmarshal(buf.Bytes(), &items); err != nil {
+		return fmt.Errorf("Cannot parse: %v: \"%v\"", string(buf.Bytes()), err.Error())
+	}
+
+	return nil
+}