Browse Source

Add API 12

Rufus Deponian 3 years ago
parent
commit
f676a8b65d
1 changed files with 61 additions and 0 deletions
  1. 61 0
      sdApi12/sdApi12.go

+ 61 - 0
sdApi12/sdApi12.go

@@ -0,0 +1,61 @@
+package sdApi12
+
+import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"strconv"
+
+	models "devel.mephi.ru/dyokunev/go-sd-models/api12"
+)
+
+var (
+	apiKey string
+)
+
+func SetApiKey(newApiKey string) {
+	apiKey = newApiKey
+}
+
+// GetRoles return filtered list of roles
+// Arguments for filtering can be set in filterRole
+// You can use these fields: PersonId, ServiceName and RoleName
+// You have to set at least one these ones: ServiceName or RoleName
+func GetRoles(filterRole models.Role) (models.Roles, error) {
+	client := &http.Client{}
+
+	req, _ := http.NewRequest("GET", "https://sd.mephi.ru/api/12/get_permissions.json", nil)
+	q := req.URL.Query()
+	q.Add("api_key", apiKey)
+	if filterRole.PersonId != 0 {
+		q.Add("subject_person_id", strconv.Itoa(filterRole.PersonId))
+	}
+	if filterRole.ServiceName != "" {
+		q.Add("service_name", filterRole.ServiceName)
+	}
+	if filterRole.RoleName != "" {
+		q.Add("permission_name", filterRole.RoleName)
+	}
+	req.URL.RawQuery = q.Encode()
+	response, err := client.Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer response.Body.Close()
+
+	var bytesArray []byte
+
+	buf := bytes.NewBuffer(bytesArray)
+	_, err = buf.ReadFrom(response.Body)
+	if err != nil {
+		return nil, err
+	}
+
+	var roles models.Roles
+	if err := json.Unmarshal(buf.Bytes(), &roles); err != nil {
+		return nil, fmt.Errorf("Cannot parse: %v: \"%v\"", string(buf.Bytes()), err.Error())
+	}
+
+	return roles, nil
+}