许多朋友开始加入golang的大本营,然后呢都是去看看golang的一些特性,问golang足够简单吗?有什么特性?能做什么?
上边那些回答不了,有些学基础的朋友很想做一些东西,然后我就写了这个静态文件服务器,可以上传下载,麻雀虽小,但是包含了很多零碎的小知识点大家一起来巩固一下基础知识吧
package mainimport ( "fmt" "HTML/template" "io" "net/http" "os" "path/filepath" "regexp" "strconv" "time")var mux map[string]func(http.ResponseWriter,*http.Request)type Myhandler struct{}type home struct { Title string}const ( Template_Dir = "./vIEw/" Upload_Dir = "./upload/")func main() { server := http.Server{ Addr: ":9090",Handler: &Myhandler{},ReadTimeout: 10 * time.Second,} mux = make(map[string]func(http.ResponseWriter,*http.Request)) mux["/"] = index mux["/upload"] = upload mux["/file"] = StaticServer server.ListenAndServe()}func (*Myhandler) Servehttp(w http.ResponseWriter,r *http.Request) { if h,ok := mux[r.URL.String()]; ok { h(w,r) return } if ok,_ := regexp.MatchString("/CSS/",r.URL.String()); ok { http.StripPrefix("/CSS/",http.fileServer(http.Dir("./CSS/"))).Servehttp(w,r) } else { http.StripPrefix("/",http.fileServer(http.Dir("./upload/"))).Servehttp(w,r) }}func upload(w http.ResponseWriter,r *http.Request) { if r.Method == "GET" { t,_ := template.Parsefiles(Template_Dir + "file.HTML") t.Execute(w,"上传文件") } else { r.ParseMultipartForm(32 << 20) file,handler,err := r.Formfile("uploadfile") if err != nil { fmt.Fprintf(w,"%v","上传错误") return } fileext := filepath.Ext(handler.filename) if check(fileext) == false { fmt.Fprintf(w,"不允许的上传类型") return } filename := strconv.FormatInt(time.Now().Unix(),10) + fileext f,_ := os.Openfile(Upload_Dir+filename,os.O_CREATE|os.O_WRONLY,0660) _,err = io.copy(f,file) if err != nil { fmt.Fprintf(w,"上传失败") return } filedir,_ := filepath.Abs(Upload_Dir + filename) fmt.Fprintf(w,filename+"上传完成,服务器地址:"+filedir) }}func index(w http.ResponseWriter,r *http.Request) { Title := home{Title: "首页"} t,_ := template.Parsefiles(Template_Dir + "index.HTML") t.Execute(w,Title)}func StaticServer(w http.ResponseWriter,r *http.Request) { http.StripPrefix("/file",r)}func check(name string) bool { ext := []string{".exe",".Js",".png"} for _,v := range ext { if v == name { return false } } return true}
github地址:http://github.com/widuu/staticserver
本文转载自我的个人博客微度网络-网络技术支持中心http://www.widuu.com/archives/02/959.html
总结以上是内存溢出为你收集整理的100行代码写一个golang上传下载静态服务器全部内容,希望文章能够帮你解决100行代码写一个golang上传下载静态服务器所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)