app.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. 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: %v", err)
  29. }
  30. }
  31. func (app *Application) LoadLanguages() {
  32. data, err := os.Open("./html/languages.json")
  33. defer data.Close()
  34. if err != nil {
  35. log.Printf("error reading languages: %v", err)
  36. return
  37. }
  38. app.Languages = make(map[string]string)
  39. JsonDecoder(data, &app.Languages)
  40. }
  41. func (app Application) CheckLanguage(language string) bool {
  42. _, ok := app.Languages[language]
  43. if !ok {
  44. return false
  45. }
  46. return true
  47. }
  48. func (app *Application) Login() {
  49. credentials, err := ioutil.ReadFile("./secrets.json")
  50. if err != nil {
  51. log.Printf("Error reading credentials: %v", err)
  52. }
  53. loginURL := app.BaseURL + "auth/login"
  54. req, err := http.NewRequest("POST", loginURL, bytes.NewBuffer(credentials))
  55. req.Header.Set("Content-Type", "application/json")
  56. client := &http.Client{}
  57. resp, err := client.Do(req)
  58. if err != nil {
  59. log.Printf("error logging in: %v", err)
  60. }
  61. defer resp.Body.Close()
  62. JsonDecoder(resp.Body, &app)
  63. app.AuthString = "?authToken=" + app.AccessToken
  64. log.Println(app.AuthString, resp.Status)
  65. }