package main
import (
"flag"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
"sort"
"sync"
"text/template"
"time"
)
const L = `<html>
<title>文件列表</title>
<body>
{{$ip := .IP}}
{{$dir := .Dir}}
<table>
{{range $k,$v := .List}}<tr><td><a href="http://{{$ip}}/{{$dir}}/{{$v.Name}}">文件名:{{$v.Name}}</a></td><td> 修改时间:{{$v.Time}}</td></tr>
{{end}}
</table>
</body>
</html>`
type info struct {
Name string
Time time.Time
}
type newlist []*info
type Dirinfo struct {
lock sync.Mutex
IP string
Dir string
List newlist
}
var x Dirinfo
var name, dir string
var path *string = flag.String("p", "/tmp", "共享的路径")
var port *string = flag.String("l", ":1789", "监听的IP:端口")
func main() {
flag.Parse()
name = filepath.Base(*path)
dir = filepath.Dir(*path)
fmt.Println("共享的目录:", *path)
http.Handle(fmt.Sprintf("/%s/", name), http.FileServer(http.Dir(dir)))
http.HandleFunc("/", router)
http.ListenAndServe(*port, nil)
}
func router(w http.ResponseWriter, r *http.Request) {
l, _ := getFilelist(*path)
x.lock.Lock()
x.Dir = name
x.List = l
x.IP = r.Host
x.lock.Unlock()
t := template.New("")
t.Parse(L)
t.Execute(w, x)
}
func getFilelist(path string) (newlist, error) {
l, err := ioutil.ReadDir(path)
if err != nil {
return []*info{}, err
}
var list []*info
for _, v := range l {
list = append(list, &info{v.Name(), v.ModTime()})
}
sort.Sort(newlist(list))
return list, nil
}
func (I newlist) Len() int {
return len(I)
}
func (I newlist) Less(i, j int) bool {
return I[i].Time.Unix() < I[j].Time.Unix()
}
func (I newlist) Swap(i, j int) {
I[i], I[j] = I[j], I[i]
}