1 Star 0 Fork 1

尹磊/Go原生搭建图片网站

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
control.go 2.33 KB
一键复制 编辑 原始数据 按行查看 历史
YinLei 提交于 2020-02-07 15:33 +08:00 . Go PhotoWebsite
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
)
/**
控制器
*/
//页面
//主页面
func IndexView(w http.ResponseWriter,r *http.Request){
html := loadHtml("./views/index.html")
w.Write(html)
}
//上传页面
func UploadView(w http.ResponseWriter,r *http.Request){
html := loadHtml("./views/upload.html")
w.Write(html)
}
//图片上传
func ApiUpload(w http.ResponseWriter,r *http.Request){
r.ParseForm()
f,h,err:= r.FormFile("file")
if err!=nil{
io.WriteString(w,"上传错误!")
return
}
t := h.Header.Get("Content-Type")
if !strings.Contains(t,"image"){
io.WriteString(w,"文件类型错误!")
return
}
os.Mkdir("./static",0666)
now := time.Now()
name := now.Format("2006-01-02150405"+path.Ext(h.Filename))
//path.Ext(h.Filename)//获取后缀名
out,err := os.Create("./static/"+name)
if err!=nil{
io.WriteString(w,"文件创建错误!")
return
}
io.Copy(out,f)
out.Close()
f.Close()
mod := Info{
Name:h.Filename,
Path: "/static/"+name,
Note:r.Form.Get("note"),
Unix:now.Unix(),
}
InfoAdd(&mod)
http.Redirect(w,r,"/list",302)
}
//详细页面
func DetailView(w http.ResponseWriter,r *http.Request){
r.ParseForm()
idStr := r.Form.Get("id")
id,_ := strconv.ParseInt(idStr,10,64)
mod,_:=InfoGet(id)
html := loadHtml("./views/detail.html")
date := time.Unix(mod.Unix,0).Format("2006年01月02日15:04:05")
html = bytes.Replace(html,[]byte("@src"),[]byte(mod.Path),1)
html = bytes.Replace(html,[]byte("@note"),[]byte(mod.Note),1)
html = bytes.Replace(html,[]byte("@unix"),[]byte(date),1)
w.Write(html)
}
//相册列表
func ApiList(w http.ResponseWriter,r *http.Request){
mods,_ := InfoList()
buf,_:=json.Marshal(mods)
w.Header().Set("Content-Type","application/json")
w.Write(buf)
}
//删除
func ApiDrop(w http.ResponseWriter,r *http.Request){
r.ParseForm()
idStr := r.Form.Get("id")
id,_:=strconv.ParseInt(idStr,10,64)
err:=InfoDelete(id)
if err!= nil {
io.WriteString(w,"删除失败")
return
}
io.WriteString(w,"删除成功")
return
}
//相册列表页面
func ListView(w http.ResponseWriter,r *http.Request){
html := loadHtml("./views/list.html")
w.Write(html)
}
/**
加载html文件
*/
func loadHtml(name string) []byte {
buf,err := ioutil.ReadFile(name)
if err != nil {
return []byte("")
}
return buf
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/yinleilei/go_to_build_a_picture_website.git
git@gitee.com:yinleilei/go_to_build_a_picture_website.git
yinleilei
go_to_build_a_picture_website
Go原生搭建图片网站
master

搜索帮助