app.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. func (app *Application) loadLanguages() {
  31. data, err := os.Open("./html/languages.json")
  32. if err != nil {
  33. log.Fatalf("Error reading languages: %s", err)
  34. }
  35. defer data.Close()
  36. app.Languages = make(map[string]string)
  37. jsonDecoder(data, &app.Languages)
  38. }
  39. func (app Application) checkLanguage(language string) bool {
  40. _, ok := app.Languages[language]
  41. return ok
  42. }
  43. func (app *Application) login() {
  44. credentials, err := ioutil.ReadFile("./secrets.json")
  45. if err != nil {
  46. log.Fatalf("Error reading credentials: %s", err)
  47. }
  48. loginURL := app.BaseURL + "auth/login"
  49. resp, err := postQuery(loginURL, credentials)
  50. if err != nil {
  51. log.Fatalf("Error logging in: %s", err)
  52. }
  53. if resp.StatusCode != 200 {
  54. log.Fatalf("Error logging in: %s", resp.Status)
  55. }
  56. defer resp.Body.Close()
  57. jsonDecoder(resp.Body, &app)
  58. app.AuthString = "?authToken=" + app.AccessToken
  59. log.Println(app.AuthString, resp.Status)
  60. }