Google Go語言實(shí)現(xiàn)http共享(帶trace)
我之前有篇文章(http://www.cnblogs.com/MikeZhang/archive/2012/03/13/httpShareGolang20120312.html)中提到過用Go語言實(shí)現(xiàn)http文件共享,這個(gè)版本的程序比python的實(shí)現(xiàn)快了點(diǎn),默認(rèn)情況下支持的客戶端多了些,但是沒有客戶訪問的trace,程序運(yùn)行過程中,感覺像是死掉了。我想改進(jìn)下,讓它有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())
- }
運(yùn)行效果如下:
1、啟動(dòng)http文件共享
2、web訪問
3、后臺(tái)trace
說明:最大支持2G文件的下載,限時(shí)為1個(gè)小時(shí),這里沒有用充分使用http協(xié)議,直接用文件io做的。時(shí)間有限,這里暫時(shí)達(dá)到了預(yù)期功能,夠局域網(wǎng)使用,這個(gè)等以后有時(shí)間了做進(jìn)一步的優(yōu)化。
原文鏈接:http://www.cnblogs.com/MikeZhang/archive/2012/08/06/httpShareGolang20120805.html
【編輯推薦】