Dmitry Yu Okunev лет назад: 6
Сommit
f0c7f53a3e
2 измененных файлов с 95 добавлено и 0 удалено
  1. 1 0
      README.md
  2. 94 0
      acdir.go

+ 1 - 0
README.md

@@ -0,0 +1 @@
+Usage example is here [https://devel.mephi.ru/dyokunev/cps-api/src/master/app/init.go](https://devel.mephi.ru/dyokunev/cps-api/src/master/app/init.go)

+ 94 - 0
acdir.go

@@ -0,0 +1,94 @@
+package acdir
+
+import (
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"strings"
+)
+
+type Entry struct {
+	Username   string `json:"login"`
+	Firstname  string
+	Lastname   string
+	Patronymic string
+	Mail       string
+	Fullname   string
+	EmpGUID    int `json:"person_id"`
+}
+
+type Entries []Entry
+
+type Error string
+
+var (
+	apiKey string
+)
+
+const (
+	ErrNoRows          = Error("Empty search result")
+	ErrUnknown0        = Error("len(entries) > 1")
+	ErrNotImplemented0 = Error("ATM, it can be filtered only by Username")
+)
+
+func (e Error) Error() string {
+	return string(e)
+}
+
+func GetEntries(entry Entry) (entries Entries, err error) {
+
+	{ // Check for non-implemented case. ATM, it can be filtered only by Username
+		entryDup := entry
+		entryDup.Username = ""
+		if (Entry{}) != entryDup {
+			err = ErrNotImplemented0
+			return
+		}
+	}
+
+	req, err := http.NewRequest("GET", fmt.Sprintf("https://sd.mephi.ru/api/3/get_person.json?api_key=%s&force_array=true&login=%s", apiKey, entry.Username), nil)
+	if err != nil {
+		return
+	}
+
+	client := &http.Client{}
+	resp, err := client.Do(req)
+	if err != nil {
+		return
+	}
+
+	defer resp.Body.Close()
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		return
+	}
+
+	entries = make([]Entry, 0, 65535)
+
+	decoder := json.NewDecoder(strings.NewReader(string(body)))
+	if err = decoder.Decode(&entries); err != nil {
+		return
+	}
+
+	return
+}
+
+func GetEntryByUsername(username string) (entry Entry, err error) {
+	entries, err := GetEntries(Entry{Username: username})
+	if err != nil {
+		return
+	}
+	if len(entries) > 1 {
+		return Entry{}, ErrUnknown0
+	}
+	if len(entries) == 0 {
+		return Entry{}, ErrNoRows
+	}
+
+	return entries[0], nil
+}
+
+func Init(newApiKey string) {
+	apiKey = newApiKey
+}