picRan/main.go
2024-08-08 11:12:57 +05:00

43 lines
825 B
Go

package main
import (
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
)
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 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 main() {
log.Println("Server Start")
http.HandleFunc("/", ReturnPic)
http.ListenAndServe(":3666", nil)
}