golang实现http服务器处理静态文件示例
本文实例讲述了golang实现http服务器处理静态文件的方法。分享给大家供大家参考,具体如下:
新版本更精简:
packagemain import( "flag" "log" "net/http" "os" "io" "path" "strconv" ) vardirstring varportint varstaticHandlerhttp.Handler //初始化参数 funcinit(){ dir=path.Dir(os.Args[0]) flag.IntVar(&port,"port",80,"服务器端口") flag.Parse() staticHandler=http.FileServer(http.Dir(dir)) } funcmain(){ http.HandleFunc("/",StaticServer) err:=http.ListenAndServe(":"+strconv.Itoa(port),nil) iferr!=nil{ log.Fatal("ListenAndServe:",err) } } //静态文件处理 funcStaticServer(whttp.ResponseWriter,req*http.Request){ ifreq.URL.Path!="/"{ staticHandler.ServeHTTP(w,req) return } io.WriteString(w,"hello,world!\n") }
老版本:
packagemain import( "flag" "log" "net/http" "os" "path" "strconv" ) vardirstring varportint varindexs[]string //初始化参数 funcinit(){ dir=path.Dir(os.Args[0]) flag.IntVar(&port,"port",80,"服务器端口") flag.Parse() indexs=[]string{"index.html","index.htm"} } funcmain(){ http.HandleFunc("/",StaticServer) err:=http.ListenAndServe(":"+strconv.Itoa(port),nil) iferr!=nil{ log.Fatal("ListenAndServe:",err) } } //静态文件处理 funcStaticServer(whttp.ResponseWriter,req*http.Request){ file:=dir+req.URL.Path fi,err:=os.Stat(file) ifos.IsNotExist(err){ http.NotFound(w,req) return } iferr!=nil{ http.Error(w,err.Error(),500) return } iffi.IsDir(){ ifreq.URL.Path[len(req.URL.Path)-1]!='/'{ http.Redirect(w,req,req.URL.Path+"/",301) return } for_,index:=rangeindexs{ fi,err=os.Stat(file+index) iferr!=nil{ continue } http.ServeFile(w,req,file+index) return } http.NotFound(w,req) return } http.ServeFile(w,req,file) }
希望本文所述对大家Go语言程序设计有所帮助。