2024-08-08 11:12:57 +05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"math/rand"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
2024-12-13 23:30:30 +05:00
|
|
|
"strings"
|
2024-12-10 22:54:02 +05:00
|
|
|
"text/template"
|
2024-08-08 11:12:57 +05:00
|
|
|
)
|
|
|
|
|
|
|
|
func GetPicsArray() []string {
|
|
|
|
files, err := os.ReadDir("images")
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if len(files) == 0 {
|
|
|
|
return []string{"no images"}
|
|
|
|
}
|
|
|
|
var filesNames = make([]string, len(files))
|
|
|
|
for i, file := range files {
|
|
|
|
filesNames[i] = string(file.Name())
|
|
|
|
}
|
|
|
|
return filesNames
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetRandImg() string {
|
|
|
|
picsArray := GetPicsArray()
|
|
|
|
return picsArray[rand.Intn(len(picsArray))]
|
|
|
|
}
|
|
|
|
|
2024-12-13 23:30:30 +05:00
|
|
|
func ReturnPicFilename(w http.ResponseWriter, req *http.Request) {
|
|
|
|
var picFilename io.Reader = strings.NewReader(GetRandImg())
|
2024-12-14 15:58:59 +05:00
|
|
|
log.Println("Картинка отдана")
|
2024-12-13 23:30:30 +05:00
|
|
|
io.Copy(w, picFilename)
|
|
|
|
}
|
|
|
|
|
2024-08-08 11:12:57 +05:00
|
|
|
func ReturnPic(w http.ResponseWriter, req *http.Request) {
|
|
|
|
picture, _ := os.Open(fmt.Sprintf("images/%v", GetRandImg()))
|
|
|
|
var pictureReader io.Reader = picture
|
|
|
|
io.Copy(w, pictureReader)
|
|
|
|
log.Println("Картинка отдана")
|
|
|
|
}
|
|
|
|
|
2024-12-10 22:54:02 +05:00
|
|
|
func ReturnHTML(w http.ResponseWriter, req *http.Request) {
|
2024-12-13 23:30:30 +05:00
|
|
|
htmlOpen, err := template.ParseFiles("dist/index.html")
|
2024-12-10 22:54:02 +05:00
|
|
|
if err != nil {
|
|
|
|
log.Println(err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
image := GetRandImg()
|
|
|
|
fmt.Println(image)
|
|
|
|
htmlOpen.Execute(w, image)
|
|
|
|
}
|
|
|
|
|
2024-08-08 11:12:57 +05:00
|
|
|
func main() {
|
|
|
|
log.Println("Server Start")
|
2024-12-10 22:54:02 +05:00
|
|
|
imagesDir := http.FileServer(http.Dir("images"))
|
2024-12-13 23:30:30 +05:00
|
|
|
staticDir := http.FileServer(http.Dir("dist/assets"))
|
2024-12-10 22:54:02 +05:00
|
|
|
http.Handle("/images/", http.StripPrefix("/images/", imagesDir))
|
2024-12-13 23:30:30 +05:00
|
|
|
http.Handle("/assets/", http.StripPrefix("/assets/", staticDir))
|
|
|
|
|
|
|
|
http.HandleFunc("/rand", ReturnPicFilename)
|
2024-12-10 22:54:02 +05:00
|
|
|
http.HandleFunc("/", ReturnHTML)
|
2024-08-08 11:12:57 +05:00
|
|
|
http.ListenAndServe(":3666", nil)
|
|
|
|
}
|