You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

210 lines
5.5 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
//"fmt"
"fmt"
"os"
"path/filepath"
_ "github.com/go-sql-driver/mysql" // для связи с mysql
"github.com/jmoiron/sqlx"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/accesslog"
)
var db *sqlx.DB
var selected string = ""
// Read the example and its comments carefully.
func makeAccessLog() *accesslog.AccessLog {
// Initialize a new access log middleware.
ac := accesslog.File("./access.log")
// Remove this line to disable logging to console:
// ac.AddOutput(os.Stdout)
// The default configuration:
// ac.Delim = '|'
// ac.TimeFormat = "2006-01-02 15:04:05"
// ac.Async = false
// ac.IP = true
// ac.BytesReceivedBody = true
// ac.BytesSentBody = true
// ac.BytesReceived = false
// ac.BytesSent = false
// ac.BodyMinify = true
// ac.RequestBody = true
// ac.ResponseBody = false
// ac.KeepMultiLineError = true
// ac.PanicLog = accesslog.LogHandler
// Default line format if formatter is missing:
// Time|Latency|Code|Method|Path|IP|Path Params Query Fields|Bytes Received|Bytes Sent|Request|Response|
//
// Set Custom Formatter:
// ac.SetFormatter(&accesslog.JSON{
// Indent: " ",
// HumanTime: true,
// })
// ac.SetFormatter(&accesslog.CSV{})
ac.SetFormatter(&accesslog.Template{Text: "{{.Code}} {{.Method}} {{.Path}} {{.Query}}\n"})
return ac
}
func newApp(db *sqlx.DB) *iris.Application {
app := iris.Default()
app.HandleDir("/", iris.Dir("./app/dist"))
app.HandleDir("/images/get/", iris.Dir("d:/pics"))
app.Logger().SetOutput(os.Stdout)
//imagesAPI := app.Party("/img")
//imagesAPI.Use(iris.Compression)
// app.Get("/albums", albums(db))
app.PartyFunc("/album", albums(db))
app.PartyFunc("/images", images(db))
//app.Run(iris.TLS("127.0.0.1:443", "mycert.crt", "mykey.key"))
// $ openssl req -new -newkey rsa:4096 -x509 -sha256 \
// -days 365 -nodes -out mycert.crt -keyout mykey.key
return app
}
func main() {
ac := makeAccessLog()
defer ac.Close() // Close the underline file.
db = openDB()
app := newApp(db)
app.UseRouter(ac.Handler)
app.Listen(":8080")
}
func openDB() *sqlx.DB {
// fmt.Printf("открываю БД nano-svelte\n")
db, err := sqlx.Open("mysql", "itman:X753951x@(xigmanas:3306)/sea")
checkError("open db", err)
return db
}
type Album struct {
Seria string
Cnt int
Hash string
}
func getAlbums(db *sqlx.DB) []Album {
cmd := "call getAlbums()"
var albums []Album
err := db.Select(&albums, cmd)
checkError("get albums", err)
return albums
}
func albums(db *sqlx.DB) func(iris.Party) {
return func(r iris.Party) {
r.Get("/list", func(ctx iris.Context) {
ctx.Application().Logger().Infof("запрос списка альбомов ")
albums := getAlbums(db)
ctx.JSON(albums)
})
r.Get("/dest/{album}", func(ctx iris.Context) {
selected = ctx.Params().Get("album")
ctx.Application().Logger().Infof("выбор альбома: %s", selected)
ctx.JSON(iris.Map{"status": iris.StatusOK})
})
r.Get("/get/{album}", func(ctx iris.Context) {
album := ctx.Params().Get("album")
if album == "local" {
ctx.Application().Logger().Infof("запрос локального альбома")
images := getLocalImages()
ctx.JSON(images)
} else {
ctx.Application().Logger().Infof("запрос альбома: %s", album)
ctx.JSON(iris.Map{"message": "hello", "status": iris.StatusOK})
}
})
}
}
func images(db *sqlx.DB) func(iris.Party) {
return func(r iris.Party) {
r.Get("/list", func(ctx iris.Context) {
ctx.Application().Logger().Infof("запрос списка картинок")
images := getLocalImages()
ctx.JSON(images)
})
r.Get("/trash/{id}", func(ctx iris.Context) {
id := ctx.Params().Get("id")
filename := ctx.Request().URL.Query().Get("filename")
ctx.Application().Logger().Infof("удаление картинки[%s]: %s", id, filename)
err := moveFile(filename, "trash")
checkError("trash file", err)
ctx.JSON(iris.Map{"status": iris.StatusOK})
})
r.Get("/move/{id}", func(ctx iris.Context) {
id := ctx.Params().Get("id")
filename := ctx.Request().URL.Query().Get("filename")
ctx.Application().Logger().Infof("перемещение картинки[%s]: %s в [%s]",
id, filename, selected)
err := moveFile(filename, selected)
checkError("move file", err)
ctx.JSON(iris.Map{"status": iris.StatusOK})
})
}
}
// перемещает файл из oldLocation в newLocation
func moveFile(filename, album string) error {
albumDir := filepath.Join("d:/pics-move", album)
if _, err := os.Stat(albumDir); os.IsNotExist(err) {
err := os.Mkdir(albumDir, 0755)
checkError("mkdir", err)
}
oldLocation := filepath.Join("d:/pics", filename)
newLocation := filepath.Join(albumDir, filename)
err := os.Rename(oldLocation, newLocation)
if err != nil {
return err
}
return nil
}
func getLocalImages() []Image {
images := []Image{}
list, err := os.ReadDir("d:/pics")
checkError("read dir", err)
for n, f := range list {
img := Image{Id: n, Url: "/images/get/" + f.Name()}
images = append(images, img)
}
return images
}
type Image struct {
Id int
Url string
}
// func list(ctx iris.Context) {
// images := []Image{
// {Id: 1, Url: "первый"},
// {Id: 2, Url: "второй"},
// }
// ctx.Application().Logger().Infof("Person: %#+v", "Проверка")
// ctx.JSON(images)
// }
// ============================ разные утилиты ==========================
// Проверяет наличие ошибки
func checkError(src string, err error) {
if err != nil {
fmt.Printf("(%s): %s\n", src, err)
os.Exit(1)
}
}