app.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "os"
  10. "strings"
  11. "time"
  12. )
  13. // Application stores main information needed to run the app
  14. type Application struct {
  15. Name, AccessToken, Sid, BaseURL, AuthString string
  16. Languages map[string]string
  17. Delay time.Duration
  18. }
  19. // SetBaseURL sets base URL for API endpoint.
  20. func (app *Application) SetBaseURL(url string) {
  21. if !strings.HasSuffix(url, "/") {
  22. url += "/"
  23. }
  24. app.BaseURL = url
  25. }
  26. // JSONDecoder decodes json to given interface, borrowed from SO.
  27. func JSONDecoder(data io.ReadCloser, target interface{}) {
  28. decoder := json.NewDecoder(data)
  29. err := decoder.Decode(target)
  30. if err != nil {
  31. log.Printf("Error reading json: %v", err)
  32. }
  33. }
  34. // LoadLanguages loads languages from languages.json to map.
  35. func (app *Application) LoadLanguages() {
  36. data, err := os.Open("./html/languages.json")
  37. defer data.Close()
  38. if err != nil {
  39. log.Fatalf("Error reading languages: %v", err)
  40. }
  41. app.Languages = make(map[string]string)
  42. JSONDecoder(data, &app.Languages)
  43. }
  44. // CheckLanguage checks if language is in the map.
  45. func (app Application) CheckLanguage(language string) bool {
  46. _, ok := app.Languages[language]
  47. if !ok {
  48. return false
  49. }
  50. return true
  51. }
  52. // Login logs into the API and sets AuthString.
  53. func (app *Application) Login() {
  54. credentials, err := ioutil.ReadFile("./secrets.json")
  55. if err != nil {
  56. log.Fatalf("Error reading credentials: %v", err)
  57. }
  58. loginURL := app.BaseURL + "auth/login"
  59. req, err := http.NewRequest("POST", loginURL, bytes.NewBuffer(credentials))
  60. req.Header.Set("Content-Type", "application/json")
  61. client := &http.Client{}
  62. resp, err := client.Do(req)
  63. if err != nil {
  64. log.Fatalf("Error logging in: %v", err)
  65. }
  66. if resp.StatusCode != 200 {
  67. log.Fatalf("Error logging in: %v", resp.Status)
  68. }
  69. defer resp.Body.Close()
  70. JSONDecoder(resp.Body, &app)
  71. app.AuthString = "?authToken=" + app.AccessToken
  72. log.Println(app.AuthString, resp.Status)
  73. }