打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
一百行golng代码写一个静态文件服务器 | 微度网络

 一直讲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}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Golang构建简单web框架
Go语言HTTP Server源码分析
gin 源码阅读(1) - gin 与 net/http 的关系
理解Go/Golang http库的请求解析过程
Go语言写Web 应用程序
用示例和应用程序了解必要的Golang库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服