]> Sergey Matveev's repositories - sgblog.git/blob - cmd/sgblog/img.go
More compact Base64 ETag
[sgblog.git] / cmd / sgblog / img.go
1 // SGBlog -- Git-backed CGI/UCSPI blogging/phlogging/gemlogging engine
2 // Copyright (C) 2020-2024 Sergey Matveev <stargrave@stargrave.org>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU Affero General Public License as
6 // published by the Free Software Foundation, version 3 of the License.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU Affero General Public License
14 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 package main
17
18 import (
19         "log"
20         "os"
21         "path"
22         "strings"
23
24         "github.com/go-git/go-git/v5/plumbing"
25 )
26
27 type Img struct {
28         Path string
29         Alt  string
30         Size int64
31         Typ  string
32 }
33
34 var ImgTypes = map[string]string{
35         ".jxl":  "image/jxl",
36         ".webp": "image/webp",
37 }
38
39 func listImgs(cfg *Cfg, what plumbing.Hash) (out []Img) {
40         if cfg.ImgPath == "" {
41                 return nil
42         }
43         w := what.String()
44         sub := path.Join(w[:2], w[2:4], w[4:])
45         ents, err := os.ReadDir(path.Join(cfg.ImgPath, sub))
46         if err != nil {
47                 return nil
48         }
49         out = make([]Img, 0, len(ents))
50         for _, ent := range ents {
51                 name := ent.Name()
52                 ext := path.Ext(name)
53                 info, err := ent.Info()
54                 if err != nil {
55                         log.Println("imgs: Info():", err)
56                         continue
57                 }
58                 typ := ImgTypes[ext]
59                 if typ == "" {
60                         typ = "application/octet-stream"
61                 }
62                 out = append(out, Img{
63                         Path: path.Join(sub, strings.ReplaceAll(ent.Name(), " ", "%20")),
64                         Alt:  strings.TrimSuffix(name, ext),
65                         Size: info.Size(),
66                         Typ:  typ,
67                 })
68         }
69         return
70 }