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.
 
 
 
 
 

119 lines
2.6 KiB

package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
type (
// Meal contains the info about a meals
Meal struct {
Category string `json:"category"`
Price string `json:"price"`
Title string `json:"title"`
}
// Menu contains all info to menues in a mensa on one day
Menu struct {
Day int `json:"day"`
Mensa string `json:"mensa"`
Meals []Meal `json:"meals"`
Date string `json:"date"`
}
)
var (
mensen = map[string]string{
"Zentralmensa": "zentralmensa",
"Nordmensa": "nordmensa",
"Mensa+am+Turm": "turmmensa",
"Mensa+Italia": "mensaitalia",
"Bistro+HAWK": "bistrohawk",
}
trimRegex = regexp.MustCompile(`\s{2,}`)
)
func main() {
path := "./"
if len(os.Args) == 2 {
path = os.Args[1] + "/"
}
for mensa := range mensen {
for day := 1; day < 8; day = day + 1 {
menu, err := operate(mensa, day)
if err != nil {
fmt.Println(err.Error())
return
}
content, err := json.Marshal(menu)
if err != nil {
fmt.Println(err.Error())
return
}
err = ioutil.WriteFile(fmt.Sprintf("%s/%s.%v.json", path, mensen[mensa], day), content, 0644)
if err != nil {
fmt.Println(err.Error())
return
}
}
}
}
func writeToFile(content []byte) error {
err := ioutil.WriteFile(os.Args[1], content, 0644)
if err != nil {
return err
}
return nil
}
func operate(mensa string, day int) (Menu, error) {
currentDay := int(time.Now().Weekday()) // week starts on sunday in go, but thats not relevant, because the canteen is closed on sunday
push := 0
if currentDay > day {
push = 1
}
document, err := goquery.NewDocument(fmt.Sprintf("http://www.studentenwerk-goettingen.de/speiseplan.html?no_cache=1&day=%v&push=%v&selectmensa=%s", day, push, mensa))
if err != nil {
return Menu{}, err
}
meals, err := parseMeals(document)
if err != nil {
return Menu{}, err
}
date := parseDate(document)
return Menu{Day: day, Mensa: mensa, Meals: meals, Date: date}, nil
}
func parseDate(doc *goquery.Document) string {
return strip(doc.Find("#speise-head2_datum").Text())
}
func strip(old string) string {
return strings.TrimSpace(trimRegex.ReplaceAllString(old, " "))
}
func parseMeals(doc *goquery.Document) ([]Meal, error) {
meals := []Meal{}
doc.Find("table.speise-tblmain tbody tr").Each(func(i int, s *goquery.Selection) {
meal := Meal{
Category: strip(s.Find(".ext_sits_preis").Text()), // yes, really preis
Title: strip(s.Find(".ext_sits_essen").Text()),
}
meals = append(meals, meal)
})
return meals, nil
}