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

本地调试3.0

parent 69e59d57
......@@ -2,11 +2,8 @@ package controller
import (
"backend/model"
"fmt"
"math/rand"
"mime/multipart"
"net/http"
"os"
"time"
"github.com/labstack/echo/v4"
......@@ -14,15 +11,6 @@ import (
"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")
/*
......@@ -82,6 +70,8 @@ func GetFileContentType(fileType string) string {
StrRet = "application/x-tex"
case ".md":
StrRet = "text/x-markdown"
default:
StrRet = fileType
}
return StrRet
}
......@@ -110,71 +100,21 @@ func SetCookie(c echo.Context, cookie *http.Cookie, sid string, maxAge int, time
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)
*/
func overflow(dst *os.File, threshold int64) bool {
// 获取文件大小,
fi, err := dst.Stat()
if err != nil {
logrus.Println(err)
}
func overflow(info *File, threshold int) bool {
len := len(info.Content)
// 大小比较
if fi.Size() > threshold {
return false
} else {
if len > threshold {
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)
cookie, _ := c.Cookie("User")
var sid string
......@@ -189,35 +129,10 @@ func DBupdate(c echo.Context, filePath string, info *File) (string, string) {
//num,_=strconv.ParseUint(GetSetting("maxDefaultAccess"), 10, 64)
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
}
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 {
// 类型判断
......
......@@ -4,7 +4,6 @@ import (
"backend/app/response"
"backend/model"
"fmt"
"io"
"net/http"
"time"
......@@ -13,6 +12,7 @@ import (
)
type File struct {
Content string `json:"content" form:"content" query:"content"`
FileName string `json:"fileName" form:"fileName" query:"fileName"`
FileType string `json:"fileType" form:"fileType" query:"fileType"`
Expiration int `json:"expiration" form:"expiration" query:"expiration"`
......@@ -35,35 +35,18 @@ func Ping(c echo.Context) error {
// sessionId不直接绑定,通过cookie传
func RecvFile(c echo.Context) error {
info := new(File)
src, err := srcRead(c, info)
if err != nil {
return response.SendResponse4(c, err) // log在srcRead里进行
if err := c.Bind(info); err != nil {
return err
}
info.Time = timeAssign(info.Time) // 默认时间
// 创建目标文件,就是我们打算把用户上传的文件保存到什么地方
// info.Filename 参数指的是我们以用户上传的文件名,作为目标文件名,也就是服务端保存的文件名跟用户上传的文件名一样
dst, filePath := dstCreate(info)
//dst, _ := dstCreate(info)
defer dst.Close()
if !overflow(dst, 8*1024*1024) {
return c.HTML(http.StatusOK, "<p>error:文件上传失败: 文件大小超过8MB</p>")
if overflow(info, 8*1024*1024) {
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
//sid := "fakesid" //
//url := "fakeurl" //
//cookie := new(http.Cookie)
return response.SendResponse2(c, http.StatusOK, GetFileContentType(info.FileType), fmt.Sprintf("文件上传成功: %s", info.FileName), url)
_, url := DBupdate(c, info) // 不分配uid
return response.SendResponse2(c, http.StatusOK, fmt.Sprintf("文件上传成功: %s", info.FileName), info.FileName, GetFileContentType(info.FileType), url)
}
/*
......@@ -80,29 +63,31 @@ func SendFile(c echo.Context) error {
info.Time = timeAssign(info.Time) // 默认时间为当前半小时后
cookie, _ := c.Cookie("User")
cookieMsg := ""
if cookie == nil {
c.HTML(http.StatusBadRequest, "没有cookie,已分配.\n")
cookieMsg = "没有cookie,已分配.\n"
cookie = new(http.Cookie)
SetCookie(c, cookie, IdGen(8), 1800, time.Time{})
}
// 鉴权
stat := Autheticate(cookie, info.Url, info.Passwd, info.Time) // 包含创建链接Createlink
// response
switch stat {
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: // 鉴权通过
info.FileType = TypeComplement(info.FileType) // 格式化后缀,仿止出错
//stat:=model.Createlink(cookie.Value,info.Passwd,info.Url,info.Time)
filePath := model.Findlink(info.Url)
data := readFile(filePath)
c.JSON(http.StatusOK, info)
return response.SendResponse3(c, http.StatusOK, GetFileContentType(info.FileType), data) // 返回数据
data := model.Find1(info.Url, "content") // 文件内容
typ := model.Find1(info.Url, "fileType") // 文件类型
name := model.Find1(info.Url, "fileName") // 文件名
return response.SendResponse3(c, http.StatusOK, cookieMsg+"success", name, GetFileContentType(typ), data) // 返回数据
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:
return c.HTML(http.StatusUnauthorized, "请进行身份验证")
return response.SendResponse(c, http.StatusUnauthorized, cookieMsg+"error:内容过期", "") //401
//return c.HTML(http.StatusUnauthorized, "请进行身份验证")
}
return nil
}
......
......@@ -21,7 +21,7 @@ func InitWebFramework() {
}
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("http://xlab.zju.edu.cn/test/pastebin/group-1:80")) // 启动服务,注意默认端口80不能省略,需要域名解析,config
}
......
......@@ -14,9 +14,18 @@ type Response 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"`
Type string `json:"type"`
Url string `json:"url"`
Msg string `json:"msg"`
Name string `json:"fileName"`
Type string `json:"fileType"`
Data interface{} `json:"data"`
}
......@@ -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{
Code: code,
Msg: msg,
Name: name,
Type: typ,
Url: url,
Data: data,
})
}
func SendResponse3(c echo.Context, code int, typ string, data ...interface{}) error {
return c.JSON(http.StatusOK, Response2{
func SendResponse3(c echo.Context, code int, msg string, name string, typ string, data ...interface{}) error {
return c.JSON(http.StatusOK, Response3{
Code: code,
Msg: msg,
Name: name,
Type: typ,
Data: data,
})
......
......@@ -58,20 +58,26 @@ func Findlink(_url string) string {
if err != nil {
logrus.Error(err)
}
return p.Route
return p.S
}
// 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{
Route: _Route,
Time: _Time,
Passwd: _Passwd,
Date: time.Now(),
Time1: _Time1,
Time2: 0,
Url1: _url,
ID: id1,
S: _S,
Time: _Time,
Passwd: _Passwd,
Date: time.Now(),
Time1: _Time1,
Time2: 0,
Url1: _url,
Filetype: _Filetype,
Filename: _Filename,
}
DB.Create(&p)
}
......@@ -121,6 +127,21 @@ func Find(sid string, _url string) bool {
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")
/*//*随机生成字符串
......@@ -188,3 +209,11 @@ func CreatelinkFirstTime(sid string, _url string, _Time1 time.Time) {
}
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 (
)
type Content struct {
gorm.Model
Route string
ID int64 `gorm:"primarykey"`
S string
Time uint
Passwd string
Date time.Time
......@@ -15,6 +15,8 @@ type Content struct {
Time1 time.Time
Time2 uint
Url1 string
Filetype string
Filename string
}
type Sid struct {
......
......@@ -24,10 +24,7 @@ DROP TABLE IF EXISTS `contents`;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `contents` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`created_at` datetime(3) DEFAULT NULL,
`updated_at` datetime(3) DEFAULT NULL,
`deleted_at` datetime(3) DEFAULT NULL,
`route` longtext,
`s` longtext,
`time` bigint unsigned DEFAULT NULL,
`passwd` longtext,
`date` datetime(3) DEFAULT NULL,
......@@ -35,8 +32,9 @@ CREATE TABLE `contents` (
`time1` datetime(3) DEFAULT NULL,
`time2` bigint unsigned DEFAULT NULL,
`url1` longtext,
PRIMARY KEY (`id`),
KEY `idx_contents_deleted_at` (`deleted_at`)
`filetype` longtext,
`filename` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;
......@@ -87,7 +85,6 @@ CREATE TABLE `sids` (
`created_at` datetime(3) DEFAULT NULL,
`updated_at` datetime(3) DEFAULT NULL,
`deleted_at` datetime(3) DEFAULT NULL,
`time` datetime(3) DEFAULT NULL,
`s` longtext,
PRIMARY KEY (`id`),
KEY `idx_sids_deleted_at` (`deleted_at`)
......@@ -165,4 +162,5 @@ UNLOCK TABLES;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!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