app.go 1.7 KB

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