app.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. import (
  3. "encoding/json"
  4. "io"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "strings"
  9. "time"
  10. )
  11. // Application stores main information needed to run the app
  12. type Application struct {
  13. Name, AccessToken, Sid, BaseURL, AuthString string
  14. Languages map[string]string
  15. Delay time.Duration
  16. }
  17. // SetBaseURL sets base URL for API endpoint.
  18. func (app *Application) SetBaseURL(url string) {
  19. if !strings.HasSuffix(url, "/") {
  20. url += "/"
  21. }
  22. app.BaseURL = url
  23. }
  24. // JSONDecoder decodes json to given interface, borrowed from SO.
  25. func JSONDecoder(data io.ReadCloser, target interface{}) {
  26. decoder := json.NewDecoder(data)
  27. err := decoder.Decode(target)
  28. if err != nil {
  29. log.Printf("Error reading json: %v", err)
  30. }
  31. }
  32. // LoadLanguages loads languages from languages.json to map.
  33. func (app *Application) LoadLanguages() {
  34. data, err := os.Open("./html/languages.json")
  35. if err != nil {
  36. log.Fatalf("Error reading languages: %v", err)
  37. }
  38. defer data.Close()
  39. app.Languages = make(map[string]string)
  40. JSONDecoder(data, &app.Languages)
  41. }
  42. // CheckLanguage checks if language is in the map.
  43. func (app Application) CheckLanguage(language string) bool {
  44. _, ok := app.Languages[language]
  45. if !ok {
  46. return false
  47. }
  48. return true
  49. }
  50. // Login logs into the API and sets AuthString.
  51. func (app *Application) Login() {
  52. credentials, err := ioutil.ReadFile("./secrets.json")
  53. if err != nil {
  54. log.Fatalf("Error reading credentials: %v", err)
  55. }
  56. loginURL := app.BaseURL + "auth/login"
  57. resp, err := postQuery(loginURL, credentials)
  58. if err != nil {
  59. log.Fatalf("Error logging in: %v", err)
  60. }
  61. if resp.StatusCode != 200 {
  62. log.Fatalf("Error logging in: %v", resp.Status)
  63. }
  64. defer resp.Body.Close()
  65. JSONDecoder(resp.Body, &app)
  66. app.AuthString = "?authToken=" + app.AccessToken
  67. log.Println(app.AuthString, resp.Status)
  68. }