-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
78 lines (67 loc) · 1.96 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
)
var (
url string
calName string
re = regexp.MustCompile(`(BEGIN:VEVENT.*?END:VEVENT%%)`)
keywords = []string{"SUMMARY:Away", "SUMMARY:Tentative", "SUMMARY:Free"}
)
func fetchCalendar(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(bodyBytes), nil
}
func processCalendar(bodyString string) string {
bodyString = strings.Replace(bodyString, "\r\n", "%%", -1) // join to make regex easier
matches := re.FindAllStringSubmatch(bodyString, -1)
for _, match := range matches {
fullMatch := match[0]
for _, keyword := range keywords {
if strings.Contains(fullMatch, keyword) {
bodyString = strings.Replace(bodyString, fullMatch, "", -1)
break
}
}
}
bodyString = strings.Replace(bodyString, "%%", "\r\n", -1) // split back to separate lines
return bodyString
}
func handler(w http.ResponseWriter, r *http.Request) {
bodyString, err := fetchCalendar(url)
if err != nil {
log.Println("Error fetching calendar:", err)
return
}
bodyString = processCalendar(bodyString)
reCalName := regexp.MustCompile(`X-WR-CALNAME:Calendar`)
bodyString = reCalName.ReplaceAllString(bodyString, fmt.Sprintf("X-WR-CALNAME:%s", calName)) // rename the calendar
fmt.Fprint(w, bodyString)
}
func main() {
url = os.Getenv("URL")
if url == "" {
log.Fatal("URL is not set.")
}
calName = os.Getenv("DISPLAY_NAME")
if calName == "" {
calName = "My Calendar"
}
fmt.Fprint(os.Stdout, "Value of URL: \n", url)
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}