我之前有篇文章(http://www.cnblogs.com/MikeZhang/archive/2012/03/13/httpShareGolang20120312.html)中提到過用Go語言實現http文件共享,這個版本的程序比python的實現快了點,默認情況下支持的客戶端多了些,但是沒有客戶訪問的trace,程序運行過程中,感覺像是死掉了。我想改進下,讓它有trace。
代碼如下:
/* File : httpShareWithTrace.go Author : Mike E-Mail : Mike_Zhang@live.com */ package main import( "fmt" "net/http" "io/ioutil" "log" "time" "os" "strings" ) func getFilelist(path string) string { m_files,err := ioutil.ReadDir(path) if err !=nil{ // println( "Get filelist error !" ) return"" } var strRet string for _,f := range m_files { // println(f.Name(),f.IsDir()) if path == "./" { strRet += "<p><a href=\""+path+""+f.Name() +" \">" + f.Name() + "</a></p>" }else{ strRet += "<p><a href=\""+path[1:]+"/"+f.Name() +" \">" + f.Name() + "</a></p>" } } return strRet } func Handler( w http.ResponseWriter,r *http.Request ){ println("Request ",r.URL.Path," from ",r.RemoteAddr) // path := r.URL.Path[1:] path := "." + r.URL.Path if path == "./favicon.ico" {http.NotFound(w,r);return} if path == "./" || getFilelist(path) != "" {fmt.Fprintf( w,"%s",getFilelist(path));return} fin,err := os.Open(path) defer fin.Close() if err != nil {fmt.Fprintf( w,"404 : Not found" );return} readLen := 1024 * 1024 buf := make([]byte,readLen) startPos := 0 println("Transfer file ",path," ... ") for { n,err := fin.ReadAt(buf,int64(startPos)) fmt.Fprintf(w,"%s",buf[:n]) if 0 == n || err != nil {break} startPos += readLen } } func main(){ port := "8080"//Default port if len(os.Args)>1 { port = strings.Join(os.Args[1:2],"")} http.HandleFunc( "/",Handler) s := &http.Server{ Addr: ":"+port, ReadTimeout: 1 * time.Hour, WriteTimeout: 1 * time.Hour, MaxHeaderBytes: (1 << 31) - 1 , //Max file size is 2048M } println("Listening on port ",port,"...") log.Fatal(s.ListenAndServe()) }
運行效果如下:
1、啟動http文件共享

2、web訪問

3、后台trace

說明:最大支持2G文件的下載,限時為1個小時,這里沒有用充分使用http協議,直接用文件io做的。時間有限,這里暫時達到了預期功能,夠局域網使用,這個等以后有時間了做進一步的優化。
