package main import ( "fmt" "io" "log" "math/rand" "net/http" "os" "strings" "text/template" ) 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))] } func ReturnPicFilename(w http.ResponseWriter, req *http.Request) { var picFilename io.Reader = strings.NewReader(GetRandImg()) io.Copy(w, picFilename) } 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("Картинка отдана") } func ReturnHTML(w http.ResponseWriter, req *http.Request) { htmlOpen, err := template.ParseFiles("dist/index.html") if err != nil { log.Println(err.Error()) return } image := GetRandImg() fmt.Println(image) htmlOpen.Execute(w, image) } func main() { log.Println("Server Start") imagesDir := http.FileServer(http.Dir("images")) staticDir := http.FileServer(http.Dir("dist/assets")) http.Handle("/images/", http.StripPrefix("/images/", imagesDir)) http.Handle("/assets/", http.StripPrefix("/assets/", staticDir)) http.HandleFunc("/rand", ReturnPicFilename) http.HandleFunc("/", ReturnHTML) http.ListenAndServe(":3666", nil) }