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

114 lines
2.7 KiB

package main
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"regexp"
)
// var t = template.Must(template.ParseFiles("tmpl/layouts/base.html", "tmpl/index.html", "tmpl/blog.html", "tmpl/about.html", "tmpl/contact.html", ))
var validImg = regexp.MustCompile("^/info/([\\w_\\- ]+)")
var exhibit Exhibition
func main() {
exhibit.Pics = make(map[string]Picture)
http.HandleFunc("/", handleIndex)
http.HandleFunc("/blog", handleBlog)
http.HandleFunc("/about", handleAbout)
http.HandleFunc("/contact", handleContact)
http.HandleFunc("/info/", handleInfo)
http.Handle("/inc/", http.StripPrefix("/inc/", http.FileServer(http.Dir("inc"))))
log.Fatalln(http.ListenAndServe(":8080", nil))
}
type Picture struct {
Name string
Author string
Size string
Tools string
Date string
Desc string
BlogLink string
}
type Exhibition struct {
Pics map[string]Picture
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
exhibit.parseExhibitions("./data")
t, _ := template.ParseFiles("tmpl/layouts/index.html", "tmpl/gallery.html", "tmpl/header.html")
t.Execute(w, exhibit)
}
func handleBlog(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("tmpl/layouts/base.html", "tmpl/soon.html", "tmpl/header.html")
t.Execute(w, nil)
}
func handleAbout(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("tmpl/layouts/base.html", "tmpl/soon.html", "tmpl/header.html")
t.Execute(w, nil)
}
func handleContact(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("tmpl/layouts/base.html", "tmpl/soon.html", "tmpl/header.html")
t.Execute(w, nil)
}
func handleInfo(w http.ResponseWriter, r *http.Request) {
imgName := validImg.FindStringSubmatch(r.URL.Path)
if imgName == nil {
http.NotFound(w, r)
return
}
img, ok := exhibit.Pics[imgName[1]]
if !ok {
http.NotFound(w, r)
return
}
info, err := json.Marshal(img)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(info)
}
// file, _ := json.MarshalIndent(ex.Pics, "", " ")
// err := ioutil.WriteFile(dir+"/dg1.json", file, 0644)
// if err != nil {
// fmt.Println("WRITE", err)
// }
// load the exhibition data into the struct
func (ex *Exhibition) parseExhibitions(dir string) {
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Println("E1", err)
return
}
for _, f := range files {
if !f.IsDir() {
var pics []Picture
content, err := ioutil.ReadFile(dir + "/" + f.Name())
if err != nil {
fmt.Println("E2", err)
}
err = json.Unmarshal(content, &pics)
if err != nil {
fmt.Println("E3", err)
}
for _, pic := range pics {
ex.Pics[pic.Name] = pic
}
}
}
}