Init: lab4 done
This commit is contained in:
48
utils/urlFile.go
Normal file
48
utils/urlFile.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func LoadUrls(filename string) ([]string, error) {
|
||||
file, err := os.OpenFile(filename, os.O_RDONLY, 0644)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return []string{}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("failed to open file, %w", err)
|
||||
}
|
||||
|
||||
b, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read file, %w", err)
|
||||
}
|
||||
|
||||
var res []string
|
||||
if err := json.Unmarshal(b, &res); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal from json, %w", err)
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func SaveUrls(filename string, urls []string) error {
|
||||
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file, %w", err)
|
||||
}
|
||||
|
||||
b, err := json.Marshal(urls)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal to json, %w", err)
|
||||
}
|
||||
|
||||
if _, err := file.Write(b); err != nil {
|
||||
return fmt.Errorf("failed to write to file, %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user