Go 环境部署
Linux下环境配置
从官网获取Linux下的发布包
编辑 ~/.bashrc 文件新增如下配置
1 2 3
| export GOROOT=/root/go export GOPATH=/root/go export GOPATH=$GOPATH:/root/loolob_blog/liry_web_go/
|
刷新配置
- 注意:GOROOT为go发布包所在路径,GOPATH除了有发布包所在路径外,还要有自己的go工程的所在目录
Web Server 开发
Go Web Server 开发,采用轻量级的Web框架Gin
文件路由
文件服务器主要功能是上传下载和获取文件列表,核心接口为”/upload”,”/list”,”/download”
拉取文件列表
基本逻辑就是,server启动时读取本地有哪些文件,然后生成一个数据结构保存在内存中
收到list的Post请求后,将文件信息封装成一个json返回给前端
1 2 3 4 5 6 7 8 9 10 11
| func (u *FileList) Bind() { u.Ge.GET("/api/list", u.exec) }
func (u *FileList) exec(c *gin.Context) { log.Println("请求文件列表")
items := api.FileListCtr.Items
c.JSON(http.StatusOK, items) }
|
处理文件上传
收到upload的Post请求后,将接受到的文件存到本地
唯一注意点就是,为防止文件重名和相同文件重复上传,存文件到本地时,将文件名改为其MD5值存储
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| func (u *Upload) Bind() { u.Ge.POST("/api/upload", u.exec) }
func (u *Upload) exec(c *gin.Context) { log.Println("请求上传文件")
form, _ := c.MultipartForm() files := form.File["upload[]"]
if len(files) > 0 { for _, file := range files { log.Println("收到多个文件:", file.Filename) u.saveUploadedFile(file) } } else { file, _ := c.FormFile("file") log.Println("收到单个文件:", file.Filename) u.saveUploadedFile(file) }
c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) }
|
处理文件下载
收到download的Get请求后,将本地文件丢给浏览器
唯一注意的点就是,需要用FileAttachment回传文件给浏览器,这个方法可以指定文件的名字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| func (u *Download) Bind() { u.Ge.GET("/api/download", u.execGet) }
func (u *Download) execGet(c *gin.Context) { log.Println("请求下载文件") md5 := c.Query("md5") if len(md5) <= 0 { log.Println("下载请求解析失败") c.String(http.StatusNotFound, "获取文件失败") return }
items := api.FileListCtr.Items
it, _ := utils.ListFind(items, func(i interface{}) bool { return i.(config.FileItem).Md5 == md5 }) if it == nil { log.Println("下载请求解析失败") c.String(http.StatusNotFound, "获取文件失败") return } log.Println("下载请求解析完成:", it.(config.FileItem).Name) c.FileAttachment(config.PahtSave+it.(config.FileItem).Md5, it.(config.FileItem).Name) }
|
工程发布