app.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "strings"
  10. "time"
  11. )
  12. // Application stores main information needed to run the app
  13. type Application struct {
  14. Name, AccessToken, Sid, BaseURL, AuthString string
  15. Languages map[string]string
  16. Delay time.Duration
  17. }
  18. func (app *Application) setBaseURL(url string) {
  19. if !strings.HasSuffix(url, "/") {
  20. url += "/"
  21. }
  22. app.BaseURL = url
  23. }
  24. func jsonDecoder(data io.ReadCloser, target interface{}) error {
  25. decoder := json.NewDecoder(data)
  26. return decoder.Decode(target)
  27. }
  28. func (app *Application) loadLanguages() {
  29. data, err := os.Open("./html/languages.json")
  30. if err != nil {
  31. log.Fatalf("Error reading languages: %s", err)
  32. }
  33. defer data.Close()
  34. app.Languages = make(map[string]string)
  35. jsonDecoder(data, &app.Languages)
  36. }
  37. func (app Application) checkLanguage(language string) bool {
  38. _, ok := app.Languages[language]
  39. return ok
  40. }
  41. func (app *Application) login() (bool, error) {
  42. credentials, err := ioutil.ReadFile("./secrets.json")
  43. if err != nil {
  44. return false, fmt.Errorf("Error reading credentials: %s", err)
  45. }
  46. loginURL := app.BaseURL + "auth/login"
  47. resp, err := postQuery(loginURL, credentials)
  48. if err != nil {
  49. return false, fmt.Errorf("Error logging in: %s", err)
  50. }
  51. defer resp.Body.Close()
  52. if resp.StatusCode != 200 {
  53. return false, fmt.Errorf("Error logging in: %s", resp.Status)
  54. }
  55. jsonDecoder(resp.Body, &app)
  56. app.AuthString = "?authToken=" + app.AccessToken
  57. log.Println(app.AuthString, resp.Status)
  58. return true, nil
  59. }