acdir.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package acdir
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strings"
  8. )
  9. type Entry struct {
  10. Username string `json:"login"`
  11. Firstname string
  12. Lastname string
  13. Patronymic string
  14. Mail string
  15. Fullname string
  16. EmpGUID int `json:"person_id"`
  17. }
  18. type Entries []Entry
  19. type Error string
  20. var (
  21. apiKey string
  22. )
  23. const (
  24. ErrNoRows = Error("Empty search result")
  25. ErrUnknown0 = Error("len(entries) > 1")
  26. ErrNotImplemented0 = Error("ATM, it can be filtered only by Username")
  27. )
  28. func (e Error) Error() string {
  29. return string(e)
  30. }
  31. func GetEntries(entry Entry) (entries Entries, err error) {
  32. { // Check for non-implemented case. ATM, it can be filtered only by Username
  33. entryDup := entry
  34. entryDup.Username = ""
  35. if (Entry{}) != entryDup {
  36. err = ErrNotImplemented0
  37. return
  38. }
  39. }
  40. 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)
  41. if err != nil {
  42. return
  43. }
  44. client := &http.Client{}
  45. resp, err := client.Do(req)
  46. if err != nil {
  47. return
  48. }
  49. defer resp.Body.Close()
  50. body, err := ioutil.ReadAll(resp.Body)
  51. if err != nil {
  52. return
  53. }
  54. entries = make([]Entry, 0, 65535)
  55. decoder := json.NewDecoder(strings.NewReader(string(body)))
  56. if err = decoder.Decode(&entries); err != nil {
  57. return
  58. }
  59. return
  60. }
  61. func GetEntryByUsername(username string) (entry Entry, err error) {
  62. entries, err := GetEntries(Entry{Username: username})
  63. if err != nil {
  64. return
  65. }
  66. if len(entries) > 1 {
  67. return Entry{}, ErrUnknown0
  68. }
  69. if len(entries) == 0 {
  70. return Entry{}, ErrNoRows
  71. }
  72. return entries[0], nil
  73. }
  74. func Init(newApiKey string) {
  75. apiKey = newApiKey
  76. }