You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.1 KiB

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "strings"
  8. "github.com/PuerkitoBio/goquery"
  9. )
  10. type (
  11. // Meal contains the info about a meals
  12. Meal struct {
  13. Category string `json:"category"`
  14. Price string `json:"price"`
  15. Title string `json:"title"`
  16. }
  17. // Menu contains all info to menues in a mensa on one day
  18. Menu struct {
  19. Day int `json:"day"`
  20. Mensa string `json:"mensa"`
  21. Meals []Meal `json:"meals"`
  22. }
  23. )
  24. var (
  25. mensen = map[string]string{
  26. "Zentralmensa": "zentralmensa",
  27. "Nordmensa": "nordmensa",
  28. "Mensa+am+Turm": "turmmensa",
  29. "Mensa+Italia": "mensaitalia",
  30. "Bistro+HAWK": "bistrohawk",
  31. }
  32. )
  33. func main() {
  34. path := "./"
  35. if len(os.Args) == 2 {
  36. path = os.Args[1] + "/"
  37. }
  38. for mensa := range mensen {
  39. for day := 1; day < 8; day = day + 1 {
  40. menu, err := operate(mensa, day)
  41. if err != nil {
  42. fmt.Println(err.Error())
  43. return
  44. }
  45. content, err := json.Marshal(menu)
  46. if err != nil {
  47. fmt.Println(err.Error())
  48. return
  49. }
  50. err = ioutil.WriteFile(fmt.Sprintf("%s/%s.%v.json", path, mensen[mensa], day), content, 0644)
  51. if err != nil {
  52. fmt.Println(err.Error())
  53. return
  54. }
  55. }
  56. }
  57. }
  58. func writeToFile(content []byte) error {
  59. err := ioutil.WriteFile(os.Args[1], content, 0644)
  60. if err != nil {
  61. return err
  62. }
  63. return nil
  64. }
  65. func operate(mensa string, day int) (Menu, error) {
  66. meals, err := parseHTML(fmt.Sprintf("http://www.studentenwerk-goettingen.de/speiseplan.html?no_cache=1&day=%vpush=0&selectmensa=%s", day, mensa))
  67. if err != nil {
  68. return Menu{}, err
  69. }
  70. return Menu{Day: day, Mensa: mensa, Meals: meals}, nil
  71. }
  72. func strip(old string) string {
  73. new := strings.Replace(old, "\t", "", -1)
  74. new = strings.Replace(new, "\n", "", -1)
  75. return new
  76. }
  77. func parseHTML(url string) ([]Meal, error) {
  78. doc, err := goquery.NewDocument(url)
  79. if err != nil {
  80. return nil, err
  81. }
  82. meals := []Meal{}
  83. doc.Find("table.speise-tblmain tbody tr").Each(func(i int, s *goquery.Selection) {
  84. meal := Meal{
  85. Category: strip(s.Find(".ext_sits_preis").Text()), // yes, really preis
  86. Title: strip(s.Find(".ext_sits_essen").Text()),
  87. }
  88. meals = append(meals, meal)
  89. })
  90. return meals, nil
  91. }