分享
  1. 首页
  2. 文章

一百行golng代码写一个静态文件服务器

widuu · · 2073 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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

12

未经允许,不得转载本站任何文章:微度网络 » 一百行golng代码写一个静态文件服务器


有疑问加站长微信联系(非本文作者)

本文来自:微度网络

感谢作者:widuu

查看原文:一百行golng代码写一个静态文件服务器

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
2073 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏