<pre style="margin-top: 0px; margin-bottom: 0px;"><span style=" font-weight:600; color:#000080;">package</span><span style=" color:#c0c0c0;"> </span>main
import (
"flag"
"fmt"
"net/http"
"os/exec"
"path/filepath"
"strings"
"sync"
"text/template"
)
const L = `<html>
<title>文件列表</title>
<body>
{{$ip := .IP}}
{{$dir := .Dir}}
{{range $k,$v := .List}}<a href="http://{{$ip}}/{{$dir}}/{{$v}}">{{$v}}</a><br>
{{end}}
</body>
</html>`
var path *string = flag.String("p", "/tmp", "共享的路径")
type Dirinfo struct {
lock sync.Mutex
IP string
Dir string
List []string
}
var x Dirinfo
var name, dir string
func main() {
flag.Parse()
name = filepath.Base(*path)
dir = filepath.Dir(*path)l := list(*path)
x.Dir = name
x.List = l
fmt.Println("共享的目录:", *path)
http.Handle(fmt.Sprintf("/%s/", name), http.FileServer(http.Dir(dir)))
http.HandleFunc("/", router)
http.ListenAndServe(":1789", nil)
}
func router(w http.ResponseWriter, r *http.Request) {
x.lock.Lock()
x.IP = r.Host
x.lock.Unlock()
t := template.New("")
t.Parse(L)
t.Execute(w, x)
}
func list(path string) []string {
cmd := exec.Command("ls", "-t", path)
b, _ := cmd.Output()
l := strings.Split(string(b), "\n")
return l
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-05 06:17:34