package filelisting

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

const prefix = "/app/"

type userError string

func (e userError) Error() string {
	return e.Message()
}

func (e userError) Message() string {
	return string(e)
}

func FileList(writer http.ResponseWriter, request *http.Request) error {

	fmt.Println(" this is FileList func   ")
	if strings.Index(request.URL.Path, prefix) != 0 {
		//return  errors.New(" path must start  with "+prefix)
		return userError(" path must start  with " + prefix)
	}

	// app 获取 app/后面的字符串 后跟文件名
	path := request.URL.Path[len("/app/"):]
	file, err := os.Open(path)

	if err != nil {
		//panic(err)
		//处理没有文件的错误
		/*http.Error(writer,
			err.Error(),
			http.StatusInternalServerError)
		return*/
		return err

	}
	defer file.Close()

	all, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}
	writer.Write(all)
	return nil
}
