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

前端之家收集整理的这篇文章主要介绍了关于Go的一个文件目录共享应用实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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]
}
原文链接:https://www.f2er.com/go/190311.html

猜你在找的Go相关文章