Commit 9191002b authored by chenhan wang's avatar chenhan wang
Browse files

本地调试3.0

parent 69e59d57
...@@ -2,11 +2,8 @@ package controller ...@@ -2,11 +2,8 @@ package controller
import ( import (
"backend/model" "backend/model"
"fmt"
"math/rand" "math/rand"
"mime/multipart"
"net/http" "net/http"
"os"
"time" "time"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
...@@ -14,15 +11,6 @@ import ( ...@@ -14,15 +11,6 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
) )
// 如果没有对应文件夹就建立
func catalogBuild(fileType string) error {
err := os.Mkdir("pastebin/backend/files/"+fileType, 0666)
if err != nil {
return err
}
return nil
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
/* /*
...@@ -82,6 +70,8 @@ func GetFileContentType(fileType string) string { ...@@ -82,6 +70,8 @@ func GetFileContentType(fileType string) string {
StrRet = "application/x-tex" StrRet = "application/x-tex"
case ".md": case ".md":
StrRet = "text/x-markdown" StrRet = "text/x-markdown"
default:
StrRet = fileType
} }
return StrRet return StrRet
} }
...@@ -110,71 +100,21 @@ func SetCookie(c echo.Context, cookie *http.Cookie, sid string, maxAge int, time ...@@ -110,71 +100,21 @@ func SetCookie(c echo.Context, cookie *http.Cookie, sid string, maxAge int, time
return nil return nil
} }
func srcRead(c echo.Context, info *File) (src multipart.File, err error) {
file, err := c.FormFile("file")
if err != nil {
logrus.Println(err)
return nil, err
}
// 打开用户上传的文件
src, err = file.Open()
if err != nil {
logrus.Println(err)
return nil, err
}
defer src.Close()
if err = c.Bind(info); err != nil {
logrus.Println(err)
return nil, err
}
info.FileName = file.Filename
return src, nil
}
func dstCreate(info *File) (dst *os.File, filePath string) {
info.FileType = TypeComplement(info.FileType)
filePath = "./files/" + info.FileType + "/" + info.FileName
dst, err := os.Create(filePath)
if err != nil {
// 是否目录不完整引起的问题
if !os.IsExist(err) {
if catalogBuild(info.FileType) != nil {
logrus.Println(err)
return nil, ""
}
dst, err = os.Create(filePath)
if err != nil {
logrus.Println(err)
return nil, ""
}
}
}
return dst, filePath
}
/* /*
* 判断文件大小是否超过阈值(threshold,单位B) * 判断文件大小是否超过阈值(threshold,单位B)
*/ */
func overflow(dst *os.File, threshold int64) bool { func overflow(info *File, threshold int) bool {
// 获取文件大小, len := len(info.Content)
fi, err := dst.Stat()
if err != nil {
logrus.Println(err)
}
// 大小比较 // 大小比较
if fi.Size() > threshold { if len > threshold {
return false
} else {
return true return true
} else {
return false
} }
} }
func DBupdate(c echo.Context, filePath string, info *File) (string, string) { func DBupdate(c echo.Context, info *File) (string, string) {
url := "http://pastebin/" + IdGen(8) url := "http://pastebin/" + IdGen(8)
cookie, _ := c.Cookie("User") cookie, _ := c.Cookie("User")
var sid string var sid string
...@@ -189,35 +129,10 @@ func DBupdate(c echo.Context, filePath string, info *File) (string, string) { ...@@ -189,35 +129,10 @@ func DBupdate(c echo.Context, filePath string, info *File) (string, string) {
//num,_=strconv.ParseUint(GetSetting("maxDefaultAccess"), 10, 64) //num,_=strconv.ParseUint(GetSetting("maxDefaultAccess"), 10, 64)
info.MaxAccess = 30 // 设置最大默认可访问次数 info.MaxAccess = 30 // 设置最大默认可访问次数
} }
model.Savetext(filePath, info.MaxAccess, info.Passwd, info.Time, url) model.Savetext(info.Content, info.MaxAccess, info.Passwd, info.Time, url, info.FileType, info.FileName)
return sid, url return sid, url
} }
func readFile(filePath string) string {
src, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
}
fi, err := src.Stat()
if err != nil {
fmt.Println(err)
}
defer func() {
src.Close()
}()
data := make([]byte, fi.Size())
_, err = src.Read(data)
if err != nil {
fmt.Println(err)
}
// 信息隐去
//c.JSON(http.StatusOK, info)
return string(data)
}
// 格式化后缀,仿止出错 // 格式化后缀,仿止出错
func TypeComplement(typ string) string { func TypeComplement(typ string) string {
// 类型判断 // 类型判断
......
...@@ -4,7 +4,6 @@ import ( ...@@ -4,7 +4,6 @@ import (
"backend/app/response" "backend/app/response"
"backend/model" "backend/model"
"fmt" "fmt"
"io"
"net/http" "net/http"
"time" "time"
...@@ -13,6 +12,7 @@ import ( ...@@ -13,6 +12,7 @@ import (
) )
type File struct { type File struct {
Content string `json:"content" form:"content" query:"content"`
FileName string `json:"fileName" form:"fileName" query:"fileName"` FileName string `json:"fileName" form:"fileName" query:"fileName"`
FileType string `json:"fileType" form:"fileType" query:"fileType"` FileType string `json:"fileType" form:"fileType" query:"fileType"`
Expiration int `json:"expiration" form:"expiration" query:"expiration"` Expiration int `json:"expiration" form:"expiration" query:"expiration"`
...@@ -35,35 +35,18 @@ func Ping(c echo.Context) error { ...@@ -35,35 +35,18 @@ func Ping(c echo.Context) error {
// sessionId不直接绑定,通过cookie传 // sessionId不直接绑定,通过cookie传
func RecvFile(c echo.Context) error { func RecvFile(c echo.Context) error {
info := new(File) info := new(File)
src, err := srcRead(c, info) if err := c.Bind(info); err != nil {
if err != nil { return err
return response.SendResponse4(c, err) // log在srcRead里进行
} }
info.Time = timeAssign(info.Time) // 默认时间 info.Time = timeAssign(info.Time) // 默认时间
// 创建目标文件,就是我们打算把用户上传的文件保存到什么地方
// info.Filename 参数指的是我们以用户上传的文件名,作为目标文件名,也就是服务端保存的文件名跟用户上传的文件名一样
dst, filePath := dstCreate(info)
//dst, _ := dstCreate(info)
defer dst.Close()
if !overflow(dst, 8*1024*1024) { if overflow(info, 8*1024*1024) {
return c.HTML(http.StatusOK, "<p>error:文件上传失败: 文件大小超过8MB</p>") return response.SendResponse(c, http.StatusForbidden, "error:文件上传失败: 文件大小超过8MB.", "")
} }
// 这里将用户上传的文件复制到服务端的目标文件
if _, err = io.Copy(dst, src); err != nil {
logrus.Println(err)
return err
}
// api 分配
// 更新数据库 // 更新数据库
_, url := DBupdate(c, filePath, info) // 不分配uid _, url := DBupdate(c, info) // 不分配uid
//sid := "fakesid" // return response.SendResponse2(c, http.StatusOK, fmt.Sprintf("文件上传成功: %s", info.FileName), info.FileName, GetFileContentType(info.FileType), url)
//url := "fakeurl" //
//cookie := new(http.Cookie)
return response.SendResponse2(c, http.StatusOK, GetFileContentType(info.FileType), fmt.Sprintf("文件上传成功: %s", info.FileName), url)
} }
/* /*
...@@ -80,29 +63,31 @@ func SendFile(c echo.Context) error { ...@@ -80,29 +63,31 @@ func SendFile(c echo.Context) error {
info.Time = timeAssign(info.Time) // 默认时间为当前半小时后 info.Time = timeAssign(info.Time) // 默认时间为当前半小时后
cookie, _ := c.Cookie("User") cookie, _ := c.Cookie("User")
cookieMsg := ""
if cookie == nil { if cookie == nil {
c.HTML(http.StatusBadRequest, "没有cookie,已分配.\n") cookieMsg = "没有cookie,已分配.\n"
cookie = new(http.Cookie) cookie = new(http.Cookie)
SetCookie(c, cookie, IdGen(8), 1800, time.Time{}) SetCookie(c, cookie, IdGen(8), 1800, time.Time{})
} }
// 鉴权 // 鉴权
stat := Autheticate(cookie, info.Url, info.Passwd, info.Time) // 包含创建链接Createlink stat := Autheticate(cookie, info.Url, info.Passwd, info.Time) // 包含创建链接Createlink
// response
switch stat { switch stat {
case 0: case 0:
return c.HTML(http.StatusForbidden, "error:密码错误") // 403 return response.SendResponse(c, http.StatusForbidden, cookieMsg+"error:密码错误", "") //403
//return c.JSON(http.StatusForbidden, "error:密码错误") // 403
case 1: // 鉴权通过 case 1: // 鉴权通过
info.FileType = TypeComplement(info.FileType) // 格式化后缀,仿止出错 data := model.Find1(info.Url, "content") // 文件内容
//stat:=model.Createlink(cookie.Value,info.Passwd,info.Url,info.Time) typ := model.Find1(info.Url, "fileType") // 文件类型
filePath := model.Findlink(info.Url) name := model.Find1(info.Url, "fileName") // 文件名
data := readFile(filePath) return response.SendResponse3(c, http.StatusOK, cookieMsg+"success", name, GetFileContentType(typ), data) // 返回数据
c.JSON(http.StatusOK, info)
return response.SendResponse3(c, http.StatusOK, GetFileContentType(info.FileType), data) // 返回数据
case 2: case 2:
return c.HTML(http.StatusGone, "error:内容过期") return response.SendResponse(c, http.StatusGone, cookieMsg+"error:内容过期", "") //410
//return c.HTML(http.StatusGone, "error:内容过期")
case 3: case 3:
return c.HTML(http.StatusUnauthorized, "请进行身份验证") return response.SendResponse(c, http.StatusUnauthorized, cookieMsg+"error:内容过期", "") //401
//return c.HTML(http.StatusUnauthorized, "请进行身份验证")
} }
return nil return nil
} }
......
...@@ -21,7 +21,7 @@ func InitWebFramework() { ...@@ -21,7 +21,7 @@ func InitWebFramework() {
} }
func StartServer() { func StartServer() {
e.Logger.Fatal(e.Start(controller.GetSetting("url"))) // 启动服务,注意默认端口80不能省略 e.Logger.Fatal(e.Start(controller.GetSetting("testurl"))) // 启动服务,注意默认端口80不能省略
//e.Logger.Fatal(e.Start("127.0.0.1:80")) // 启动服务,注意默认端口80不能省略 //e.Logger.Fatal(e.Start("127.0.0.1:80")) // 启动服务,注意默认端口80不能省略
//e.Logger.Fatal(e.Start("http://xlab.zju.edu.cn/test/pastebin/group-1:80")) // 启动服务,注意默认端口80不能省略,需要域名解析,config //e.Logger.Fatal(e.Start("http://xlab.zju.edu.cn/test/pastebin/group-1:80")) // 启动服务,注意默认端口80不能省略,需要域名解析,config
} }
......
...@@ -14,9 +14,18 @@ type Response struct { ...@@ -14,9 +14,18 @@ type Response struct {
} }
type Response2 struct { type Response2 struct {
Code int `json:"code"`
Msg string `json:"msg"`
Name string `json:"fileName"`
Type string `json:"fileType"`
Url string `json:"url"`
}
type Response3 struct {
Code int `json:"code"` Code int `json:"code"`
Type string `json:"type"` Msg string `json:"msg"`
Url string `json:"url"` Name string `json:"fileName"`
Type string `json:"fileType"`
Data interface{} `json:"data"` Data interface{} `json:"data"`
} }
...@@ -28,18 +37,21 @@ func SendResponse(c echo.Context, code int, msg string, data ...interface{}) err ...@@ -28,18 +37,21 @@ func SendResponse(c echo.Context, code int, msg string, data ...interface{}) err
}) })
} }
func SendResponse2(c echo.Context, code int, typ string, url string, data ...interface{}) error { func SendResponse2(c echo.Context, code int, msg string, name string, typ string, url string, data ...interface{}) error {
return c.JSON(http.StatusOK, Response2{ return c.JSON(http.StatusOK, Response2{
Code: code, Code: code,
Msg: msg,
Name: name,
Type: typ, Type: typ,
Url: url, Url: url,
Data: data,
}) })
} }
func SendResponse3(c echo.Context, code int, typ string, data ...interface{}) error { func SendResponse3(c echo.Context, code int, msg string, name string, typ string, data ...interface{}) error {
return c.JSON(http.StatusOK, Response2{ return c.JSON(http.StatusOK, Response3{
Code: code, Code: code,
Msg: msg,
Name: name,
Type: typ, Type: typ,
Data: data, Data: data,
}) })
......
...@@ -58,20 +58,26 @@ func Findlink(_url string) string { ...@@ -58,20 +58,26 @@ func Findlink(_url string) string {
if err != nil { if err != nil {
logrus.Error(err) logrus.Error(err)
} }
return p.Route return p.S
} }
// save text information // save text information
// 保存文本和文件信息 // 保存文本和文件信息
func Savetext(_Route string, _Time uint, _Passwd string, _Time1 time.Time, _url string) { func Savetext(_S string, _Time uint, _Passwd string, _Time1 time.Time, _url string, _Filetype string, _Filename string) {
var id1 int64
DB.Model(&Content{}).Count(&id1)
id1++
p := Content{ p := Content{
Route: _Route, ID: id1,
Time: _Time, S: _S,
Passwd: _Passwd, Time: _Time,
Date: time.Now(), Passwd: _Passwd,
Time1: _Time1, Date: time.Now(),
Time2: 0, Time1: _Time1,
Url1: _url, Time2: 0,
Url1: _url,
Filetype: _Filetype,
Filename: _Filename,
} }
DB.Create(&p) DB.Create(&p)
} }
...@@ -121,6 +127,21 @@ func Find(sid string, _url string) bool { ...@@ -121,6 +127,21 @@ func Find(sid string, _url string) bool {
return false return false
} }
// 通过url查询文件类型
func Find1(_url string, key string) string {
var p Content
DB.First(&p, "Url1 = ?", _url)
switch key {
case "content":
return p.S
case "fileType":
return p.Filetype
case "fileName":
return p.Filename
}
return ""
}
//var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789") //var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789")
/*//*随机生成字符串 /*//*随机生成字符串
...@@ -188,3 +209,11 @@ func CreatelinkFirstTime(sid string, _url string, _Time1 time.Time) { ...@@ -188,3 +209,11 @@ func CreatelinkFirstTime(sid string, _url string, _Time1 time.Time) {
} }
DB.Create(&sid1) DB.Create(&sid1)
} }
/*
func Test() {
var p Content
var Url2 string = "1234"
DB.First(&p, "url1 = ?", Url2)
fmt.Println(Checkt(p))
}*/
...@@ -6,8 +6,8 @@ import ( ...@@ -6,8 +6,8 @@ import (
) )
type Content struct { type Content struct {
gorm.Model ID int64 `gorm:"primarykey"`
Route string S string
Time uint Time uint
Passwd string Passwd string
Date time.Time Date time.Time
...@@ -15,6 +15,8 @@ type Content struct { ...@@ -15,6 +15,8 @@ type Content struct {
Time1 time.Time Time1 time.Time
Time2 uint Time2 uint
Url1 string Url1 string
Filetype string
Filename string
} }
type Sid struct { type Sid struct {
......
...@@ -24,10 +24,7 @@ DROP TABLE IF EXISTS `contents`; ...@@ -24,10 +24,7 @@ DROP TABLE IF EXISTS `contents`;
/*!50503 SET character_set_client = utf8mb4 */; /*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `contents` ( CREATE TABLE `contents` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT, `id` bigint unsigned NOT NULL AUTO_INCREMENT,
`created_at` datetime(3) DEFAULT NULL, `s` longtext,
`updated_at` datetime(3) DEFAULT NULL,
`deleted_at` datetime(3) DEFAULT NULL,
`route` longtext,
`time` bigint unsigned DEFAULT NULL, `time` bigint unsigned DEFAULT NULL,
`passwd` longtext, `passwd` longtext,
`date` datetime(3) DEFAULT NULL, `date` datetime(3) DEFAULT NULL,
...@@ -35,8 +32,9 @@ CREATE TABLE `contents` ( ...@@ -35,8 +32,9 @@ CREATE TABLE `contents` (
`time1` datetime(3) DEFAULT NULL, `time1` datetime(3) DEFAULT NULL,
`time2` bigint unsigned DEFAULT NULL, `time2` bigint unsigned DEFAULT NULL,
`url1` longtext, `url1` longtext,
PRIMARY KEY (`id`), `filetype` longtext,
KEY `idx_contents_deleted_at` (`deleted_at`) `filename` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */; /*!40101 SET character_set_client = @saved_cs_client */;
...@@ -87,7 +85,6 @@ CREATE TABLE `sids` ( ...@@ -87,7 +85,6 @@ CREATE TABLE `sids` (
`created_at` datetime(3) DEFAULT NULL, `created_at` datetime(3) DEFAULT NULL,
`updated_at` datetime(3) DEFAULT NULL, `updated_at` datetime(3) DEFAULT NULL,
`deleted_at` datetime(3) DEFAULT NULL, `deleted_at` datetime(3) DEFAULT NULL,
`time` datetime(3) DEFAULT NULL,
`s` longtext, `s` longtext,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
KEY `idx_sids_deleted_at` (`deleted_at`) KEY `idx_sids_deleted_at` (`deleted_at`)
...@@ -165,4 +162,5 @@ UNLOCK TABLES; ...@@ -165,4 +162,5 @@ UNLOCK TABLES;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2023-01-19 11:51:11 -- Dump completed on 2023-01-17 22:07:33
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment