package endpoints import ( "encoding/json" "fmt" "log" "net/http" "os" audio "physick.ru/culture_exam/Audio" settings "physick.ru/culture_exam/Settings" ) type Songs = struct { Name string Duration int } type SongsList struct { Songs []Songs } func (base SongsList) String() string { var outp, jsonErr = json.Marshal(base) if jsonErr != nil { return fmt.Sprintf("Failed to parse settings: %s", jsonErr.Error()) } return string(outp) } func getSongs(w http.ResponseWriter, r *http.Request) { var files, dirErr = os.ReadDir(settings.Current.SongsLocation) if dirErr != nil { log.Printf("Failed to look up songs list: %s", dirErr.Error()) w.WriteHeader(http.StatusInternalServerError) return } var outp = SongsList { Songs: make([]Songs, 0, len(files)), } for _, v := range files { var fullPath = fmt.Sprintf("%s/%s", settings.Current.SongsLocation, v.Name()) var duration, durErr = audio.GetSongDuration(fullPath) if durErr != nil { log.Printf("Failed to parse file metadata: File: %s, error: %s\n", fullPath, durErr.Error()) continue } var song = Songs { Name: v.Name(), Duration: int(duration.Seconds()), } outp.Songs = append(outp.Songs, song) } w.Header().Add("Content-Type", "application/json") fmt.Fprint(w, outp) }