cpolis/cmd/frontend/images.go

95 lines
2.4 KiB
Go
Raw Normal View History

2024-10-27 07:21:36 +01:00
package frontend
import (
"encoding/json"
"html/template"
"log"
"net/http"
b "streifling.com/jason/cpolis/cmd/backend"
)
func UploadImage(c *b.Config, s *b.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, err := getSession(w, r, c, s); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file, _, err := r.FormFile("article-image")
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
filename, err := b.SaveImage(file, c.MaxImgHeight, c.MaxImgWidth, c.PicsDir+"/")
2024-10-27 07:21:36 +01:00
if err != nil {
if err == b.ErrUnsupportedFormat {
http.Error(w, "Das Dateiformat wird nicht unterstützt.", http.StatusBadRequest)
return
}
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
url := c.Domain + "/image/serve/" + filename
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(url)
}
}
func UploadBanner(c *b.Config, s *b.CookieStore, fileKey, htmlFile, htmlTemplate string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, err := getSession(w, r, c, s); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file, _, err := r.FormFile(fileKey)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
filename, err := b.SaveImage(file, c.MaxBannerHeight, c.MaxBannerWidth, c.PicsDir+"/")
2024-10-27 07:21:36 +01:00
if err != nil {
if err == b.ErrUnsupportedFormat {
http.Error(w, "Das Dateiformat wird nicht unterstützt.", http.StatusBadRequest)
return
}
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
base64Img, err := b.ServeBase64Image(c, filename)
2024-10-27 07:21:36 +01:00
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := new(struct {
BannerImage string
URL string
})
data.BannerImage = base64Img
data.URL = c.Domain + "/image/serve/" + filename
tmpl, err := template.ParseFiles(c.WebDir + "/templates/" + htmlFile)
if err = template.Must(tmpl, err).ExecuteTemplate(w, htmlTemplate, data); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}