关于Go的一个文件目录共享应用实例
发布时间:2020-12-16 18:41:11 所属栏目:大数据 来源:网络整理
导读:package mainimport ("flag""fmt""io/ioutil""net/http""path/filepath""sort""sync""text/template""time")const L = `htmltitle文件列表/titlebody{{$ip := .IP}}{{$dir := .Dir}}table{{range $k,$v := .List}}trtda href="http://{{$ip}}/{{$dir}}/{{$v.
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] } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |