Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了100行代码写一个golang上传下载静态服务器大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

import (
    "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上传下载静态服务器所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: