app.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. func (app *Application) setBaseURL(url string) {
  18. if !strings.HasSuffix(url, "/") {
  19. url += "/"
  20. }
  21. app.BaseURL = url
  22. }
  23. // JSONDecoder decodes json to given interface, borrowed from SO.
  24. func JSONDecoder(data io.ReadCloser, target interface{}) {
  25. decoder := json.NewDecoder(data)
  26. err := decoder.Decode(target)
  27. if err != nil {
  28. log.Printf("Error reading json: %v", err)
  29. }
  30. }
  31. // LoadLanguages loads languages from languages.json to map.
  32. func (app *Application) LoadLanguages() {
  33. data, err := os.Open("./html/languages.json")
  34. if err != nil {
  35. log.Fatalf("Error reading languages: %v", err)
  36. }
  37. defer data.Close()
  38. app.Languages = make(map[string]string)
  39. JSONDecoder(data, &app.Languages)
  40. }
  41. func (app Application) checkLanguage(language string) bool {
  42. _, ok := app.Languages[language]
  43. return ok
  44. }
  45. // Login logs into the API and sets AuthString.
  46. func (app *Application) Login() {
  47. credentials, err := ioutil.ReadFile("./secrets.json")
  48. if err != nil {
  49. log.Fatalf("Error reading credentials: %v", err)
  50. }
  51. loginURL := app.BaseURL + "auth/login"
  52. resp, err := postQuery(loginURL, credentials)
  53. if err != nil {
  54. log.Fatalf("Error logging in: %v", err)
  55. }
  56. if resp.StatusCode != 200 {
  57. log.Fatalf("Error logging in: %v", resp.Status)
  58. }
  59. defer resp.Body.Close()
  60. JSONDecoder(resp.Body, &app)
  61. app.AuthString = "?authToken=" + app.AccessToken
  62. log.Println(app.AuthString, resp.Status)
  63. }