关于Go的一个文件目录共享应用实例

来源:互联网 发布:mac键盘怎么拆 编辑:程序博客网 时间:2024/06/06 12:32
package mainimport ("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 stringTime time.Time}type newlist []*infotype Dirinfo struct {lock sync.MutexIP   stringDir  stringList newlist}var x Dirinfovar name, dir stringvar 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 = namex.List = lx.IP = r.Hostx.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 []*infofor _, 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]}

1 0
原创粉丝点击