Browse Source

fix: single ReadFile fn

NhanPT 2 years ago
parent
commit
11aca2bbae
4 changed files with 12 additions and 27 deletions
  1. 1 9
      src/modules/config.go
  2. 1 9
      src/modules/content.go
  3. 9 0
      src/modules/file.go
  4. 1 9
      src/modules/language.go

+ 1 - 9
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

+ 1 - 9
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

+ 9 - 0
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 {

+ 1 - 9
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")