personal-website/libs/imglib.go
2023-05-04 01:04:29 +03:00

83 lines
1.7 KiB
Go

package libs
import (
"errors"
"net/http"
"personalwebsite/webfilesystem"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type ImagLib struct {
fs *webfilesystem.WebFileSystem
}
func NewImgLib(webfs *webfilesystem.WebFileSystem) *ImagLib {
return &ImagLib{
fs: webfs,
}
}
func ReadImage(img *webfilesystem.WebFSFile) (*Img, error) {
data, ok := img.Data.(primitive.D).Map()["srcdata"]
if !ok {
return nil, errors.New("error in file decoding")
}
bin := data.(primitive.Binary).Data
min32Data, ok := img.Data.(primitive.D).Map()["min32data"]
if !ok {
return nil, errors.New("error in file decoding")
}
min32Bin := min32Data.(primitive.Binary).Data
return &Img{
// Header: header,
Data: bin,
Miniature32: min32Bin,
}, nil
}
func (l *ImagLib) Route(route *gin.RouterGroup) {
route.GET("get", func(ctx *gin.Context) {
path := ctx.Query("path")
if path == "" {
ctx.JSON(http.StatusBadRequest, "TODO") //TODO json error struct
return
}
file, err := l.fs.Read(path)
if err != nil {
ctx.String(http.StatusInternalServerError, "TODO") //TODO
}
data := file.Data.(primitive.Binary)
ctx.Data(http.StatusOK, "image/jpeg", data.Data)
})
}
func GetBase64Image(img *Base64Img, min string) (string, error) {
imgString := ""
switch min {
case "min32":
imgString = "data:" + img.Header + ", " + img.Base64Miniature32
default:
imgString = "data:" + img.Header + ", " + img.Base64
}
return imgString, nil
}
type Base64Img struct {
Header string `bson:"header"`
Base64 string `bson:"base64"`
Base64Miniature32 string `bson:"base64min32"`
}
type Img struct {
Header string `bson:"header"`
Data []byte `bson:"srcdata"`
Miniature32 []byte `bson:"min32data"`
}