app.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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{}) {
  25. decoder := json.NewDecoder(data)
  26. err := decoder.Decode(target)
  27. if err != nil {
  28. log.Printf("Error reading json: %s", err)
  29. }
  30. }
  31. func (app *Application) loadLanguages() {
  32. data, err := os.Open("./html/languages.json")
  33. if err != nil {
  34. log.Fatalf("Error reading languages: %s", 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. func (app *Application) login() (bool, error) {
  45. credentials, err := ioutil.ReadFile("./secrets.json")
  46. if err != nil {
  47. return false, fmt.Errorf("Error reading credentials: %s", err)
  48. }
  49. loginURL := app.BaseURL + "auth/login"
  50. resp, err := postQuery(loginURL, credentials)
  51. if err != nil {
  52. return false, fmt.Errorf("Error logging in: %s", err)
  53. }
  54. defer resp.Body.Close()
  55. if resp.StatusCode != 200 {
  56. return false, fmt.Errorf("Error logging in: %s", resp.Status)
  57. }
  58. jsonDecoder(resp.Body, &app)
  59. app.AuthString = "?authToken=" + app.AccessToken
  60. log.Println(app.AuthString, resp.Status)
  61. return true, nil
  62. }