app.go 1.8 KB

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