From e76a47f98a9b664e5ad260737d1694763127f07d Mon Sep 17 00:00:00 2001 From: NhanPT Date: Sat, 18 Feb 2023 14:12:45 +0700 Subject: [PATCH 1/4] refactor code --- src/main.go | 185 ++-------------------------------------- src/modules/config.go | 11 ++- src/modules/content.go | 9 +- src/modules/file.go | 9 ++ src/modules/language.go | 6 ++ src/modules/network.go | 18 ++++ src/modules/template.go | 155 +++++++++++++++++++++++++++++++++ src/modules/weather.go | 46 ++++++++++ 8 files changed, 253 insertions(+), 186 deletions(-) create mode 100644 src/modules/network.go create mode 100644 src/modules/template.go create mode 100644 src/modules/weather.go diff --git a/src/main.go b/src/main.go index ec27ae1..ed700da 100644 --- a/src/main.go +++ b/src/main.go @@ -1,51 +1,22 @@ package main import ( - "html/template" - "io/ioutil" "log" "net/http" - "net" "os" - "path" "path/filepath" - "strings" - "time" - "github.com/fsnotify/fsnotify" docker "github.com/help-14/magma/addons/docker" healthcheckserver "github.com/help-14/magma/addons/health-check-server" "github.com/help-14/magma/modules" ) -var pwd string -var themeDir string -var clientAddress string -var appConfig modules.Config -var websiteData = struct { - Config modules.WebsiteConfig - Language modules.Language - Contents []modules.GroupData -}{} -var webTemplate *template.Template - func main() { prepare() - loadData() - go watchChanges() - - commonfs := http.FileServer(http.Dir(filepath.Join(pwd, "data"))) - http.Handle("/common/", http.StripPrefix("/common/", commonfs)) - - languagefs := http.FileServer(http.Dir(filepath.Join(pwd, "languages"))) - http.Handle("/languages/", http.StripPrefix("/languages/", languagefs)) - - th := themeHandler{} - http.Handle("/theme/", th) - - http.HandleFunc("/weather", serveWeather) - http.HandleFunc("/", serveTemplate) + modules.SetupLanguage() + modules.SetupTemplate() + modules.SetupWeather() //loadAddons() log.Println("Listening on http://localhost:7001 ...") @@ -56,75 +27,19 @@ func main() { } func prepare() { - pwd, _ = os.Getwd() - - dataPath := filepath.Join(pwd, "data") + dataPath := filepath.Join(modules.CurrentPath(), "data") os.MkdirAll(dataPath, os.ModePerm) iconPath := filepath.Join(dataPath, "icon") os.RemoveAll(iconPath) os.MkdirAll(iconPath, os.ModePerm) - modules.CopyDir(filepath.Join(pwd, "common"), dataPath, false) -} - -func RemoveIndex(s []modules.BookmarkData, index int) { - copy(s[index:], s[index+1:]) - s[len(s)-1] = modules.BookmarkData{"", "", "", false} - s = s[:len(s)-1] -} - -func pruneData() { - // Remove local ressources access - for group := 0; group < len(websiteData.Contents); group++ { - for col := 0; col < len(websiteData.Contents[group].Columns); col++ { - bookmarks := websiteData.Contents[group].Columns[col].Bookmarks - for bookmark := 0; bookmark < len(websiteData.Contents[group].Columns[col].Bookmarks); bookmark++ { - bookmarkData := websiteData.Contents[group].Columns[col].Bookmarks[bookmark] - if bookmarkData.IsLocal { - RemoveIndex(bookmarks, bookmark) - bookmark-- - } - } - websiteData.Contents[group].Columns[col].Bookmarks = bookmarks - } - } - loadTemplate() -} - -func loadData() { - appConfig = modules.LoadConfig() - websiteData.Config = appConfig.Website - websiteData.Language = modules.LoadLanguage(appConfig.Website.Language) - websiteData.Contents = modules.LoadContent().Data - - // Download icon to local and remove local ressources access - for group := 0; group < len(websiteData.Contents); group++ { - for col := 0; col < len(websiteData.Contents[group].Columns); col++ { - for bookmark := 0; bookmark < len(websiteData.Contents[group].Columns[col].Bookmarks); bookmark++ { - bookmarkData := websiteData.Contents[group].Columns[col].Bookmarks[bookmark] - if bookmarkData.IsImage() || bookmarkData.IsSVG() { - iconPath := bookmarkData.Icon - fileName := path.Base(iconPath) - if modules.DownloadFile(iconPath, filepath.Join(pwd, "data", "icon", fileName)) { - websiteData.Contents[group].Columns[col].Bookmarks[bookmark].Icon = "/common/icon/" + fileName - } - } - } - } - } - loadTemplate() -} - -func loadTemplate() { - themeDir = filepath.Join(pwd, "themes", appConfig.Website.Theme) - tmpl, _ := template.ParseFiles(filepath.Join(themeDir, "index.html")) - webTemplate = tmpl + modules.CopyDir(filepath.Join(modules.CurrentPath(), "common"), dataPath, false) } func loadAddons() { - for i := 0; i < len(appConfig.Addons); i++ { - switch addonName := appConfig.Addons[i]; addonName { + for i := 0; i < len(modules.AppConfig.Addons); i++ { + switch addonName := modules.AppConfig.Addons[i]; addonName { case "docker": docker.Setup() case "health-check-server": @@ -132,89 +47,3 @@ func loadAddons() { } } } - -func watchChanges() { - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - defer watcher.Close() - - done := make(chan bool) - go func() { - for { - select { - case event, ok := <-watcher.Events: - if !ok { - return - } - log.Println("Modified file:", event.Name) - loadData() - case err, ok := <-watcher.Errors: - if !ok { - return - } - log.Println("error:", err) - } - } - }() - - watcher.Add(filepath.Join(pwd, "data", "data.yaml")) - watcher.Add(filepath.Join(pwd, "data", "config.yaml")) - watcher.Add(filepath.Join(pwd, "themes", appConfig.Website.Theme, "index.html")) - <-done -} - -func ClientIsLocal(r *http.Request) bool { - IPAddress := net.ParseIP(r.Header.Get("X-Real-Ip")) - if IPAddress == nil { - IPAddress = net.ParseIP(r.Header.Get("X-Forwarded-For")) - } - if IPAddress == nil { - IPAddress = net.ParseIP(strings.Split(r.RemoteAddr, ":")[0]) - } - return IPAddress.IsPrivate() -} - -func serveTemplate(w http.ResponseWriter, r *http.Request) { - if ! ClientIsLocal(r) { - pruneData() - } else { - loadData() - } - webTemplate.Execute(w, websiteData) -} - -type themeHandler struct { - format string -} - -func (th themeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, strings.Replace(r.URL.Path, "/theme", themeDir, 1)) -} - -var weatherTimeOut int64 -var weatherCache []byte - -func serveWeather(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - if appConfig.OpenWeatherMap.ApiKey == "demo" { - w.Write([]byte("{\"coord\":{\"lon\":105.8085,\"lat\":21.0427},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04n\"}],\"base\":\"stations\",\"main\":{\"temp\":301.14,\"feels_like\":305.69,\"temp_min\":301.14,\"temp_max\":301.14,\"pressure\":1004,\"humidity\":83},\"visibility\":10000,\"wind\":{\"speed\":6.17,\"deg\":120},\"clouds\":{\"all\":75},\"dt\":1650981392,\"sys\":{\"type\":1,\"id\":9308,\"country\":\"VN\",\"sunrise\":1650925786,\"sunset\":1650971952},\"timezone\":25200,\"id\":1581130,\"name\":\"Hanoi\",\"cod\":200}")) - } else { - if time.Now().UnixMilli() >= weatherTimeOut { - resp, err := http.Get("https://api.openweathermap.org/data/2.5/weather?lat=" + appConfig.OpenWeatherMap.Latitude + "&lon=" + appConfig.OpenWeatherMap.Longitude + "&limit=1&appid=" + appConfig.OpenWeatherMap.ApiKey) - if err != nil { - log.Fatalln(err) - return - } - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - log.Fatalln(err) - return - } - weatherCache = body - weatherTimeOut = time.Now().UnixMilli() + 1800000 - } - w.Write(weatherCache) - } -} diff --git a/src/modules/config.go b/src/modules/config.go index fe56067..d17dd37 100644 --- a/src/modules/config.go +++ b/src/modules/config.go @@ -29,7 +29,9 @@ type OpenWeatherMapConfig struct { Latitude string `yaml:"lat"` } -func LoadConfig() Config { +var AppConfig Config + +func LoadConfig() { defaultConfig := Config{ Website: WebsiteConfig{ Title: "Magma Dashboard", @@ -41,20 +43,21 @@ func LoadConfig() Config { }, Addons: []string{}, } + AppConfig = defaultConfig yamlFile, err := ioutil.ReadFile(filepath.Join("data", "config.yaml")) if err != nil { fmt.Printf("Error reading YAML file: %s\n", err) - return defaultConfig + return } var yamlConfig Config err = yaml.Unmarshal(yamlFile, &yamlConfig) if err != nil { fmt.Printf("Error parsing YAML file: %s\n", err) - return defaultConfig + return } fmt.Println("Loaded config:", yamlConfig) - return yamlConfig + AppConfig = yamlConfig } diff --git a/src/modules/content.go b/src/modules/content.go index 3a28442..1f277b5 100644 --- a/src/modules/content.go +++ b/src/modules/content.go @@ -28,10 +28,11 @@ type ColumnData struct { } type BookmarkData struct { - Name string `yaml:"name"` - Url string `yaml:"url"` - Icon string `yaml:"icon"` - IsLocal bool `yaml:"isLocal"` + Name string `yaml:"name"` + Url string `yaml:"url"` + UrlLocal string `yaml:"urlLocal"` + Icon string `yaml:"icon"` + IsLocal bool `yaml:"isLocal"` } func LoadContent() ContentData { diff --git a/src/modules/file.go b/src/modules/file.go index 677f71c..a6635d3 100644 --- a/src/modules/file.go +++ b/src/modules/file.go @@ -7,6 +7,15 @@ import ( "os" ) +var pwd string + +func CurrentPath() string { + if len(pwd) <= 0 { + pwd, _ = os.Getwd() + } + return pwd +} + func Exists(path string) bool { if _, err := os.Stat(path); !os.IsNotExist(err) { return true diff --git a/src/modules/language.go b/src/modules/language.go index 2a9ca11..571cbca 100644 --- a/src/modules/language.go +++ b/src/modules/language.go @@ -3,11 +3,17 @@ package modules import ( "fmt" "io/ioutil" + "net/http" "path/filepath" "gopkg.in/yaml.v2" ) +func SetupLanguage() { + languagefs := http.FileServer(http.Dir(filepath.Join(CurrentPath(), "languages"))) + http.Handle("/languages/", http.StripPrefix("/languages/", languagefs)) +} + type Language struct { Greeting LanguageGreeting `yaml:"greeting"` Weather LanguageWeather `yaml:"weather"` diff --git a/src/modules/network.go b/src/modules/network.go new file mode 100644 index 0000000..22c228c --- /dev/null +++ b/src/modules/network.go @@ -0,0 +1,18 @@ +package modules + +import ( + "net" + "net/http" + "strings" +) + +func ClientIsLocal(r *http.Request) bool { + IPAddress := net.ParseIP(r.Header.Get("X-Real-Ip")) + if IPAddress == nil { + IPAddress = net.ParseIP(r.Header.Get("X-Forwarded-For")) + } + if IPAddress == nil { + IPAddress = net.ParseIP(strings.Split(r.RemoteAddr, ":")[0]) + } + return IPAddress.IsPrivate() +} diff --git a/src/modules/template.go b/src/modules/template.go new file mode 100644 index 0000000..2fec34a --- /dev/null +++ b/src/modules/template.go @@ -0,0 +1,155 @@ +package modules + +import ( + "log" + "net/http" + "path" + "path/filepath" + "strings" + "text/template" + + "github.com/fsnotify/fsnotify" +) + +func SetupTemplate() { + loadData() + go watchChanges() + + commonfs := http.FileServer(http.Dir(filepath.Join(pwd, "data"))) + http.Handle("/common/", http.StripPrefix("/common/", commonfs)) + + th := themeHandler{} + http.Handle("/theme/", th) + + http.HandleFunc("/", serveTemplate) +} + +var websiteData = struct { + Config WebsiteConfig + Language Language + Contents []GroupData + IsLocal bool +}{} +var privateContent []GroupData +var publicContent []GroupData +var webTemplate *template.Template + +func loadData() { + LoadConfig() + websiteData.Config = AppConfig.Website + websiteData.Language = LoadLanguage(AppConfig.Website.Language) + websiteData.Contents = LoadContent().Data + + // Download icon to local and remove local ressources access + for groupIndex := 0; groupIndex < len(websiteData.Contents); groupIndex++ { + group := websiteData.Contents[groupIndex] + groupDataPublic := []ColumnData{} + groupDataPrivate := []ColumnData{} + + for colIndex := 0; colIndex < len(group.Columns); colIndex++ { + column := group.Columns[colIndex] + columnDataPublic := []BookmarkData{} + columnDataPrivate := []BookmarkData{} + + for bookmarkIndex := 0; bookmarkIndex < len(column.Bookmarks); bookmarkIndex++ { + bookmarkData := column.Bookmarks[bookmarkIndex] + iconPath := bookmarkData.Icon + + //download icon + if bookmarkData.IsImage() || bookmarkData.IsSVG() { + fileName := path.Base(iconPath) + if DownloadFile(iconPath, filepath.Join(pwd, "data", "icon", fileName)) { + iconPath = "/common/icon/" + fileName + } + } + + //add to private array + if bookmarkData.IsLocal || len(bookmarkData.UrlLocal) > 0 { + url := bookmarkData.Url + if len(bookmarkData.UrlLocal) > 0 { + url = bookmarkData.UrlLocal + } + columnDataPrivate = append(columnDataPrivate, BookmarkData{bookmarkData.Name, url, bookmarkData.UrlLocal, iconPath, true}) + } + + //add to public array + if !bookmarkData.IsLocal && len(bookmarkData.Url) > 0 { + columnDataPublic = append(columnDataPublic, BookmarkData{bookmarkData.Name, bookmarkData.Url, bookmarkData.UrlLocal, iconPath, false}) + } + } + + if len(columnDataPublic) > 0 { + groupDataPublic = append(groupDataPublic, ColumnData{column.Title, columnDataPublic, column.Icon}) + } + if len(columnDataPrivate) > 0 { + groupDataPrivate = append(groupDataPrivate, ColumnData{column.Title, columnDataPrivate, column.Icon}) + } + } + + if len(groupDataPublic) > 0 { + publicContent = append(publicContent, GroupData{group.Title, groupDataPublic, group.Icon}) + } + if len(groupDataPrivate) > 0 { + privateContent = append(privateContent, GroupData{group.Title, groupDataPrivate, group.Icon}) + } + } + + loadTemplate() +} + +var themeDir string + +type themeHandler struct { + format string +} + +func (th themeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, strings.Replace(r.URL.Path, "/theme", themeDir, 1)) +} + +func loadTemplate() { + themeDir = filepath.Join(pwd, "themes", AppConfig.Website.Theme) + tmpl, _ := template.ParseFiles(filepath.Join(themeDir, "index.html")) + webTemplate = tmpl +} + +func serveTemplate(w http.ResponseWriter, r *http.Request) { + if ClientIsLocal(r) { + websiteData.Contents = privateContent + } else { + websiteData.Contents = publicContent + } + webTemplate.Execute(w, websiteData) +} + +func watchChanges() { + watcher, err := fsnotify.NewWatcher() + if err != nil { + log.Fatal(err) + } + defer watcher.Close() + + done := make(chan bool) + go func() { + for { + select { + case event, ok := <-watcher.Events: + if !ok { + return + } + log.Println("Modified file:", event.Name) + loadData() + case err, ok := <-watcher.Errors: + if !ok { + return + } + log.Println("error:", err) + } + } + }() + + watcher.Add(filepath.Join(CurrentPath(), "data", "data.yaml")) + watcher.Add(filepath.Join(CurrentPath(), "data", "config.yaml")) + watcher.Add(filepath.Join(CurrentPath(), "themes", AppConfig.Website.Theme, "index.html")) + <-done +} diff --git a/src/modules/weather.go b/src/modules/weather.go new file mode 100644 index 0000000..0420261 --- /dev/null +++ b/src/modules/weather.go @@ -0,0 +1,46 @@ +package modules + +import ( + "io/ioutil" + "log" + "net/http" + "time" +) + +func SetupWeather() { + http.HandleFunc("/weather", serveWeather) +} + +func serveWeather(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + data := GetWeather(AppConfig.OpenWeatherMap.ApiKey, AppConfig.OpenWeatherMap.Latitude, AppConfig.OpenWeatherMap.Longitude) + if data != nil { + w.Write(data) + } +} + +var weatherTimeOut int64 +var weatherCache []byte +var demoData = []byte("{\"coord\":{\"lon\":105.8085,\"lat\":21.0427},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04n\"}],\"base\":\"stations\",\"main\":{\"temp\":301.14,\"feels_like\":305.69,\"temp_min\":301.14,\"temp_max\":301.14,\"pressure\":1004,\"humidity\":83},\"visibility\":10000,\"wind\":{\"speed\":6.17,\"deg\":120},\"clouds\":{\"all\":75},\"dt\":1650981392,\"sys\":{\"type\":1,\"id\":9308,\"country\":\"VN\",\"sunrise\":1650925786,\"sunset\":1650971952},\"timezone\":25200,\"id\":1581130,\"name\":\"Hanoi\",\"cod\":200}") + +func GetWeather(apiKey string, latitude string, longitude string) []byte { + if apiKey == "demo" { + return demoData + } else { + if time.Now().UnixMilli() >= weatherTimeOut { + resp, err := http.Get("https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&limit=1&appid=" + apiKey) + if err != nil { + log.Fatalln(err) + return nil + } + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + log.Fatalln(err) + return nil + } + weatherCache = body + weatherTimeOut = time.Now().UnixMilli() + 1800000 + } + return weatherCache + } +} From e23b7d6b65e3c2689bb57428731b03f4d6324ead Mon Sep 17 00:00:00 2001 From: NhanPT Date: Sun, 19 Feb 2023 14:03:50 +0700 Subject: [PATCH 2/4] fix: themes bug --- src/main.go | 24 +++++++++++++++------ src/modules/config.go | 11 ++++++++-- src/modules/content.go | 11 ++++++++-- src/modules/file.go | 3 +-- src/modules/language.go | 15 +++++++++---- src/modules/template.go | 36 +++++++++++++++++--------------- src/modules/weather.go | 8 +++---- src/themes/flame/index.html | 12 +++++------ src/themes/simplefox/index.html | 12 +++++------ src/themes/simplenord/index.html | 12 +++++------ 10 files changed, 89 insertions(+), 55 deletions(-) diff --git a/src/main.go b/src/main.go index ed700da..85a2783 100644 --- a/src/main.go +++ b/src/main.go @@ -1,6 +1,8 @@ package main import ( + "errors" + "fmt" "log" "net/http" "os" @@ -13,17 +15,27 @@ import ( func main() { prepare() + mux := http.NewServeMux() - modules.SetupLanguage() - modules.SetupTemplate() - modules.SetupWeather() + modules.SetupLanguage(mux) + modules.SetupTemplate(mux) + modules.SetupWeather(mux) //loadAddons() + server := http.Server{ + Addr: fmt.Sprintf(":%d", 7001), + Handler: mux, + } log.Println("Listening on http://localhost:7001 ...") - err := http.ListenAndServe(":7001", nil) - if err != nil { - log.Fatal(err) + if err := server.ListenAndServe(); err != nil { + if !errors.Is(err, http.ErrServerClosed) { + fmt.Printf("error running http server: %s\n", err) + } } + // err := http.ListenAndServe(":7001", nil) + // if err != nil { + // log.Fatal(err) + // } } func prepare() { diff --git a/src/modules/config.go b/src/modules/config.go index d17dd37..5f984ac 100644 --- a/src/modules/config.go +++ b/src/modules/config.go @@ -2,7 +2,8 @@ package modules import ( "fmt" - "io/ioutil" + "io" + "os" "path/filepath" "gopkg.in/yaml.v2" @@ -45,7 +46,13 @@ func LoadConfig() { } AppConfig = defaultConfig - yamlFile, err := ioutil.ReadFile(filepath.Join("data", "config.yaml")) + file, err := os.Open(filepath.Join("data", "config.yaml")) + if err != nil { + fmt.Printf("failed reading file: %s", err) + return + } + defer file.Close() + yamlFile, err := io.ReadAll(file) if err != nil { fmt.Printf("Error reading YAML file: %s\n", err) return diff --git a/src/modules/content.go b/src/modules/content.go index 1f277b5..0c610d4 100644 --- a/src/modules/content.go +++ b/src/modules/content.go @@ -3,7 +3,8 @@ package modules import ( "fmt" "index/suffixarray" - "io/ioutil" + "io" + "os" "path/filepath" "regexp" "strings" @@ -38,7 +39,13 @@ type BookmarkData struct { func LoadContent() ContentData { emptyData := ContentData{} - yamlFile, err := ioutil.ReadFile(filepath.Join("data", "data.yaml")) + file, err := os.Open(filepath.Join("data", "data.yaml")) + if err != nil { + fmt.Printf("failed reading file: %s", err) + return emptyData + } + defer file.Close() + yamlFile, err := io.ReadAll(file) if err != nil { fmt.Printf("Error reading YAML file: %s\n", err) return emptyData diff --git a/src/modules/file.go b/src/modules/file.go index a6635d3..59fa87f 100644 --- a/src/modules/file.go +++ b/src/modules/file.go @@ -28,7 +28,6 @@ func CopyFile(source string, dest string) (err error) { if err != nil { return err } - defer sourcefile.Close() destfile, err := os.Create(dest) @@ -42,7 +41,7 @@ func CopyFile(source string, dest string) (err error) { if err == nil { sourceinfo, err := os.Stat(source) if err != nil { - err = os.Chmod(dest, sourceinfo.Mode()) + _ = os.Chmod(dest, sourceinfo.Mode()) } } diff --git a/src/modules/language.go b/src/modules/language.go index 571cbca..be838b3 100644 --- a/src/modules/language.go +++ b/src/modules/language.go @@ -2,16 +2,17 @@ package modules import ( "fmt" - "io/ioutil" + "io" "net/http" + "os" "path/filepath" "gopkg.in/yaml.v2" ) -func SetupLanguage() { +func SetupLanguage(mux *http.ServeMux) { languagefs := http.FileServer(http.Dir(filepath.Join(CurrentPath(), "languages"))) - http.Handle("/languages/", http.StripPrefix("/languages/", languagefs)) + mux.Handle("/languages/", http.StripPrefix("/languages/", languagefs)) } type Language struct { @@ -42,7 +43,13 @@ type LanguageWeather struct { } func LoadLanguage(language string) Language { - yamlFile, err := ioutil.ReadFile(filepath.Join("languages", language+".yaml")) + file, err := os.Open(filepath.Join("languages", language+".yaml")) + if err != nil { + fmt.Printf("failed reading file: %s", err) + return LoadLanguage("en") + } + defer file.Close() + yamlFile, err := io.ReadAll(file) if err != nil { fmt.Printf("Error reading YAML file: %s\n", err) return LoadLanguage("en") diff --git a/src/modules/template.go b/src/modules/template.go index 2fec34a..2a2f8a0 100644 --- a/src/modules/template.go +++ b/src/modules/template.go @@ -1,6 +1,7 @@ package modules import ( + "fmt" "log" "net/http" "path" @@ -11,17 +12,17 @@ import ( "github.com/fsnotify/fsnotify" ) -func SetupTemplate() { +func SetupTemplate(mux *http.ServeMux) { loadData() go watchChanges() - commonfs := http.FileServer(http.Dir(filepath.Join(pwd, "data"))) - http.Handle("/common/", http.StripPrefix("/common/", commonfs)) + commonfs := http.FileServer(http.Dir(filepath.Join(CurrentPath(), "data"))) + mux.Handle("/common/", http.StripPrefix("/common/", commonfs)) th := themeHandler{} - http.Handle("/theme/", th) + mux.Handle("/theme/", th) - http.HandleFunc("/", serveTemplate) + mux.HandleFunc("/", serveTemplate) } var websiteData = struct { @@ -39,6 +40,7 @@ func loadData() { websiteData.Config = AppConfig.Website websiteData.Language = LoadLanguage(AppConfig.Website.Language) websiteData.Contents = LoadContent().Data + loadTemplate() // Download icon to local and remove local ressources access for groupIndex := 0; groupIndex < len(websiteData.Contents); groupIndex++ { @@ -58,19 +60,17 @@ func loadData() { //download icon if bookmarkData.IsImage() || bookmarkData.IsSVG() { fileName := path.Base(iconPath) - if DownloadFile(iconPath, filepath.Join(pwd, "data", "icon", fileName)) { + if DownloadFile(iconPath, filepath.Join(CurrentPath(), "data", "icon", fileName)) { iconPath = "/common/icon/" + fileName } } //add to private array - if bookmarkData.IsLocal || len(bookmarkData.UrlLocal) > 0 { - url := bookmarkData.Url - if len(bookmarkData.UrlLocal) > 0 { - url = bookmarkData.UrlLocal - } - columnDataPrivate = append(columnDataPrivate, BookmarkData{bookmarkData.Name, url, bookmarkData.UrlLocal, iconPath, true}) + url := bookmarkData.Url + if len(bookmarkData.UrlLocal) > 0 { + url = bookmarkData.UrlLocal } + columnDataPrivate = append(columnDataPrivate, BookmarkData{bookmarkData.Name, url, bookmarkData.UrlLocal, iconPath, true}) //add to public array if !bookmarkData.IsLocal && len(bookmarkData.Url) > 0 { @@ -93,8 +93,6 @@ func loadData() { privateContent = append(privateContent, GroupData{group.Title, groupDataPrivate, group.Icon}) } } - - loadTemplate() } var themeDir string @@ -104,17 +102,20 @@ type themeHandler struct { } func (th themeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, strings.Replace(r.URL.Path, "/theme", themeDir, 1)) + newPath := strings.Replace(r.URL.Path, "/theme", themeDir, 1) + fmt.Println(newPath) + http.ServeFile(w, r, newPath) } func loadTemplate() { - themeDir = filepath.Join(pwd, "themes", AppConfig.Website.Theme) + themeDir = filepath.Join(CurrentPath(), "themes", AppConfig.Website.Theme) tmpl, _ := template.ParseFiles(filepath.Join(themeDir, "index.html")) webTemplate = tmpl } func serveTemplate(w http.ResponseWriter, r *http.Request) { - if ClientIsLocal(r) { + websiteData.IsLocal = ClientIsLocal(r) + if websiteData.IsLocal { websiteData.Contents = privateContent } else { websiteData.Contents = publicContent @@ -126,6 +127,7 @@ func watchChanges() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) + return } defer watcher.Close() diff --git a/src/modules/weather.go b/src/modules/weather.go index 0420261..c2e4971 100644 --- a/src/modules/weather.go +++ b/src/modules/weather.go @@ -1,14 +1,14 @@ package modules import ( - "io/ioutil" + "io" "log" "net/http" "time" ) -func SetupWeather() { - http.HandleFunc("/weather", serveWeather) +func SetupWeather(mux *http.ServeMux) { + mux.HandleFunc("/weather", serveWeather) } func serveWeather(w http.ResponseWriter, r *http.Request) { @@ -33,7 +33,7 @@ func GetWeather(apiKey string, latitude string, longitude string) []byte { log.Fatalln(err) return nil } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { log.Fatalln(err) return nil diff --git a/src/themes/flame/index.html b/src/themes/flame/index.html index a8f01eb..7ba11ce 100644 --- a/src/themes/flame/index.html +++ b/src/themes/flame/index.html @@ -91,8 +91,8 @@
{{.Name}}
From 11aca2bbaea6bd0cdc9cc7c51a5a7496c4974c81 Mon Sep 17 00:00:00 2001 From: NhanPT Date: Sun, 19 Feb 2023 14:15:02 +0700 Subject: [PATCH 3/4] fix: single ReadFile fn --- src/modules/config.go | 10 +--------- src/modules/content.go | 10 +--------- src/modules/file.go | 9 +++++++++ src/modules/language.go | 10 +--------- 4 files changed, 12 insertions(+), 27 deletions(-) diff --git a/src/modules/config.go b/src/modules/config.go index 5f984ac..b0b807b 100644 --- a/src/modules/config.go +++ b/src/modules/config.go @@ -2,8 +2,6 @@ package modules import ( "fmt" - "io" - "os" "path/filepath" "gopkg.in/yaml.v2" @@ -46,13 +44,7 @@ func LoadConfig() { } AppConfig = defaultConfig - file, err := os.Open(filepath.Join("data", "config.yaml")) - if err != nil { - fmt.Printf("failed reading file: %s", err) - return - } - defer file.Close() - yamlFile, err := io.ReadAll(file) + yamlFile, err := ReadFile(filepath.Join("data", "config.yaml")) if err != nil { fmt.Printf("Error reading YAML file: %s\n", err) return diff --git a/src/modules/content.go b/src/modules/content.go index 0c610d4..e8a785e 100644 --- a/src/modules/content.go +++ b/src/modules/content.go @@ -3,8 +3,6 @@ package modules import ( "fmt" "index/suffixarray" - "io" - "os" "path/filepath" "regexp" "strings" @@ -39,13 +37,7 @@ type BookmarkData struct { func LoadContent() ContentData { emptyData := ContentData{} - file, err := os.Open(filepath.Join("data", "data.yaml")) - if err != nil { - fmt.Printf("failed reading file: %s", err) - return emptyData - } - defer file.Close() - yamlFile, err := io.ReadAll(file) + yamlFile, err := ReadFile(filepath.Join("data", "data.yaml")) if err != nil { fmt.Printf("Error reading YAML file: %s\n", err) return emptyData diff --git a/src/modules/file.go b/src/modules/file.go index 59fa87f..2e87bb4 100644 --- a/src/modules/file.go +++ b/src/modules/file.go @@ -23,6 +23,15 @@ func Exists(path string) bool { return false } +func ReadFile(path string) ([]byte, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + return io.ReadAll(file) +} + func CopyFile(source string, dest string) (err error) { sourcefile, err := os.Open(source) if err != nil { diff --git a/src/modules/language.go b/src/modules/language.go index be838b3..763dea2 100644 --- a/src/modules/language.go +++ b/src/modules/language.go @@ -2,9 +2,7 @@ package modules import ( "fmt" - "io" "net/http" - "os" "path/filepath" "gopkg.in/yaml.v2" @@ -43,13 +41,7 @@ type LanguageWeather struct { } func LoadLanguage(language string) Language { - file, err := os.Open(filepath.Join("languages", language+".yaml")) - if err != nil { - fmt.Printf("failed reading file: %s", err) - return LoadLanguage("en") - } - defer file.Close() - yamlFile, err := io.ReadAll(file) + yamlFile, err := ReadFile(filepath.Join("languages", language+".yaml")) if err != nil { fmt.Printf("Error reading YAML file: %s\n", err) return LoadLanguage("en") From f4112ca40be17af06c0980527ebb4ce33abcb47d Mon Sep 17 00:00:00 2001 From: Nhan Phan Date: Wed, 1 Mar 2023 20:03:54 +0700 Subject: [PATCH 4/4] fix: local bookmark --- src/modules/template.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/modules/template.go b/src/modules/template.go index 2a2f8a0..0f719ad 100644 --- a/src/modules/template.go +++ b/src/modules/template.go @@ -70,7 +70,9 @@ func loadData() { if len(bookmarkData.UrlLocal) > 0 { url = bookmarkData.UrlLocal } - columnDataPrivate = append(columnDataPrivate, BookmarkData{bookmarkData.Name, url, bookmarkData.UrlLocal, iconPath, true}) + if len(url) > 0 { + columnDataPrivate = append(columnDataPrivate, BookmarkData{bookmarkData.Name, url, bookmarkData.UrlLocal, iconPath, true}) + } //add to public array if !bookmarkData.IsLocal && len(bookmarkData.Url) > 0 {