一百行golng代碼寫一個靜態檔案伺服器

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

一直講golang標準庫,不僅大家看煩了,我自己寫的都比較難受了,所以寫一個簡單的靜態檔案伺服器,裡邊有上傳下載,和簡單的html,你可以根據你自己的需求來修改~~

包含功能

  1. 靜態檔案模板
  2. 檔案上傳
  3. 檔案查看和下載

使用的包

import (    "fmt"    "html/template"    "io"    "net/http"    "os"    "path/filepath"    "regexp"    "strconv"    "time")

包含知識點

//靜態檔案伺服器http.FileServer(http.Dir("目錄"))//手工佈建服務和路由s := &http.Server{    Addr:           ":8080",    Handler:        myHandler,    ReadTimeout:    10 * time.Second,    WriteTimeout:   10 * time.Second,    MaxHeaderBytes: 1 << 20,}s.ListenAndServe();// path/filepath包的使用

麻雀雖小,但是有很多基礎知識點適合學習golang的朋友們一起玩,程式碼範例地址:http://github.com/widuu/staticserver

執行個體代碼staticserver.go

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, "%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}

未經允許,不得轉載本站任何文章:微度網路 » 一百行golng代碼寫一個靜態檔案伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.