100行代碼寫一個golang上傳下載靜態服務器

許多朋友開始加入golang的大本營,而後呢都是去看看golang的一些特性,問golang足夠簡單嗎?有什麼特性?能作什麼?css

上邊那些回答不了,有些學基礎的朋友很想作一些東西,而後我就寫了這個靜態文件服務器,能夠上傳下載,麻雀雖小,可是包含了不少零碎的小知識點你們一塊兒來鞏固一下基礎知識吧html

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, "%v", "不容許的上傳類型")
            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, "%v", "上傳失敗")
            return
        }
        filedir, _ := filepath.Abs(Upload_Dir + filename)
        fmt.Fprintf(w, "%v", 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", http.FileServer(http.Dir("./upload/"))).ServeHTTP(w, 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/staticservergit

本文轉載自個人我的博客微度網絡-網絡技術支持中心http://www.widuu.com/archives/02/959.htmlgithub

相關文章
相關標籤/搜索