Init: lab4 done
This commit is contained in:
17
utils/initDB.go
Normal file
17
utils/initDB.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"golang-lab4/models"
|
||||
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
func InitDB(db *bun.DB) {
|
||||
err := db.ResetModel(context.Background(),
|
||||
(*models.UrlState)(nil),
|
||||
)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
14
utils/success.go
Normal file
14
utils/success.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Success(w http.ResponseWriter) error {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
_, err := io.WriteString(w,
|
||||
`{"code":200, "message": "success"}`+"\n")
|
||||
return err
|
||||
}
|
||||
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