Commit 0f59208b authored by lytzjzxr's avatar lytzjzxr
Browse files

新分支/第一次

parent 967489ab
config.yaml
backend/files
\ No newline at end of file
# pastebin
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://xlab.zju.edu.cn/git/chenhan/pastebin.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://xlab.zju.edu.cn/git/chenhan/pastebin/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
.idea/**
conf.yaml
docs/**
\ No newline at end of file
package controller
import (
"net"
"net/http"
"pastebin_backend/app/response"
//"error"
"github.com/labstack/echo/v4"
//"encoding/json"
"fmt"
"io"
"os"
//"github.com/google/uuid"
//"github.com/go-playground/validator"
//"github.com/sirupsen/logrus"
)
type File struct {
FileName string `json:"fileName"`
FileType string `json:"fileType"`
Expiration int `json:"expiration"`
User string `json:"user"`
Passwd string `json:"passwd"`
//Content string `json:"content"`
}
type FileRe struct {
FileName string `json:"fileName"`
FileType string `json:"fileType"`
}
type pass struct {
User string `json:"user"`
Passwd string `json:"passwd"`
}
type Text struct {
text string `json:"text"`
}
func Ping(c echo.Context) error {
// just a demo
return response.SendResponse(c, http.StatusOK, "", "pong!")
}
// 通过用户名密码来设置cookie
func AskPasswd(c echo.Context) error {
//
info := new(pass)
if err := c.Bind(info); err != nil {
return err
}
if info.Passwd == "" || info.User == "" {
//return c.String(http.StatusBadRequest, "请输入用户名和密码")
c.String(http.StatusBadRequest, "请输入用户名和密码")
return echo.ErrBadRequest
}
// 在数据库中查找,若user存在且密码一样,重置cookie有效期
// user存在但密码不一样,密码错误或用户名已存在
// user不存在,数据库中加记录并生成一个新的cookie
SetCookie(c, info)
return c.String(http.StatusOK, "cookie设置") //
//return nil
}
// 设置cookie名为user,根据数据库分配uuid
func SetCookie(c echo.Context, info *pass) error {
/*uuid, err := uuid.NewUUID()
if err != nil {
logrus.Fatal(err)
}
cookie := new(http.Cookie)
cookie.Name = "user" // 标识为user
//cookie.Value = string(uuid) // 通过uuid和数据库,确定user是谁
cookie.Value = "tmp"
cookie.Path = "/"
// cookie有效期为3600秒
cookie.MaxAge = 3600
// 在数据库中加入 cookie记录
// 设置cookie
c.SetCookie(cookie)*/
return c.String(http.StatusOK, "cookie设置")
}
// 接收浏览器发来的文件,把文件储存在.\files\目录下
// 成功则返回上传成功,否则报错
func RecvFile(c echo.Context) error {
file, err := c.FormFile("file")
if err != nil {
return err
}
// 打开用户上传的文件
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
info := new(File)
if err = c.Bind(info); err != nil {
return err
}
// 创建目标文件,就是我们打算把用户上传的文件保存到什么地方
// file.Filename 参数指的是我们以用户上传的文件名,作为目标文件名,也就是服务端保存的文件名跟用户上传的文件名一样
if info.FileType == "" {
info.FileType = "txt"
}
filePath := "./files/" + info.FileType + "/" + file.Filename
dst, err := os.Create(filePath)
//dst, err := os.Create(file.Filename)
if err != nil {
fmt.Println(err)
return err
}
defer dst.Close()
// 这里将用户上传的文件复制到服务端的目标文件
if _, err = io.Copy(dst, src); err != nil {
return err
}
return c.HTML(http.StatusOK, fmt.Sprintf("<p>文件上传成功: %s</p>", file.Filename))
}
// 根据用户请求的文件名(不带后缀)和文件类型,返回对应文件的链接
func SendFile(c echo.Context) error {
info := new(FileRe)
if err := c.Bind(info); err != nil {
return err
}
if info.FileType == "" {
info.FileType = "txt"
}
filePath := "./files/" + info.FileType + "/" + info.FileName + "." + info.FileType
src, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
return err
}
defer func() {
src.Close()
}()
data := make([]byte, 8*1024*1024)
count, err := src.Read(data)
//return response.SendResponse(c, http.StatusOK, "", "pong!")
count = count
// 信息隐去
c.JSON(http.StatusOK, info)
return response.SendResponse(c, http.StatusOK, "msg", string(data))
//return c.HTML(http.StatusOK, fmt.Sprintf("<p>文件上传成功: %s</p>", file.Filename))w
//return nil
}
func RecvText(c echo.Context) error {
text := new(Text)
if err := c.Bind(text); err != nil {
fmt.Println(err)
return err
}
//return text.text
return nil
}
func SendText(conn net.Conn, text Text) error {
buf := []byte(text.text)
_, err := conn.Write(buf[:])
if err != nil {
fmt.Println(err)
return err
}
return nil
}
// 如果没有对应文件夹就建立
func fileTypeJudge(fileType string) error {
return nil
}
package app
import (
"pastebin_backend/utils"
//"net/http"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
)
var e *echo.Echo
func InitWebFramework() {
e = echo.New()
e.HideBanner = true
addRoutes()
e.Validator = &utils.CustomValidator{}
logrus.Info("echo framework initialized")
}
func StartServer() {
e.Logger.Fatal(e.Start("127.0.0.1:80")) // 启动服务,注意默认端口80不能省略
//e.Logger.Fatal(e.Start("pastebin:80")) // 启动服务,注意默认端口80不能省略,需要域名解析,config
}
package middleware
import (
"github.com/labstack/echo/v4"
//"http/net"
"pastebin_backend/app/controller"
)
func Auth(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
//c.Bind("User")
cookie, _ := c.Cookie("user")
if cookie == nil {
err := controller.AskPasswd(c)
if err != nil {
return nil
}
}
//c.Set("uid", cookie.Value)
c.Set("uid", 114514)
return next(c)
}
}
/*
func CookieAuth(c echo.Context) error{
cookie, err := c.Cookie()
if err != nil {
return err
}
}*/
package response
import (
"net/http"
"github.com/labstack/echo/v4"
)
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
func SendResponse(c echo.Context, code int, msg string, data ...interface{}) error{
return c.JSON(http.StatusOK, Response{
Code: code,
Msg: msg,
Data: data,
})
}
package app
import (
"pastebin_backend/app/controller"
"pastebin_backend/app/middleware"
//"pastebin_backend/model"
)
func addRoutes() {
api := e.Group("api")
api.Use(middleware.Auth)
api.GET("/ping", controller.Ping)
api.POST("/passwd",controller.AskPasswd) // 密码,返回cookie
api.POST("/file/recv",controller.RecvFile)// 接收文件
api.POST("/file/send",controller.SendFile)
api.POST("/text/recv",controller.RecvText)
api.POST("/text/send",controller.RecvText)
}
module pastebin_backend
go 1.19
require (
github.com/go-playground/validator/v10 v10.11.1
github.com/google/uuid v1.1.2
github.com/labstack/echo/v4 v4.9.1
github.com/sirupsen/logrus v1.9.0
github.com/spf13/viper v1.14.0
gorm.io/driver/mysql v1.4.4
gorm.io/gorm v1.24.2
)
require (
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-sql-driver/mysql v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/labstack/gommon v0.4.0 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/spf13/afero v1.9.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.1 // indirect
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect
golang.org/x/net v0.0.0-20221014081412-f15817d10f9b // indirect
golang.org/x/sys v0.0.0-20220908164124-27713097b956 // indirect
golang.org/x/text v0.4.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
This diff is collapsed.
// @title Golang Service Template
// @version 0.1
// @description Golang back-end service template, get started with back-end projects quickly
// @BasePath /api
package main
import (
"pastebin_backend/app"
//"pastebin_backend/app/controller"
"pastebin_backend/model"
"github.com/sirupsen/logrus"
)
func main() {
logrus.SetReportCaller(true)
model.Init()
app.InitWebFramework()
app.StartServer()
//controller.BuildSocket()
//controller.RecvFile()
}
package model
import (
"time"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
func Init() {}
func Init_() {
connectDatabase()
var err error
// insert auto-table
err = DB.AutoMigrate(&Users{})
if err != nil {
logrus.Fatal(err)
}
err = DB.AutoMigrate(&content{})
if err != nil {
logrus.Fatal(err)
}
}
func connectDatabase() {
// config
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath("./")
err := viper.ReadInConfig()
if err != nil {
logrus.Panic(err)
}
// connect to database
logInfo := viper.GetStringMapString("mysql")
sqlInfo := logInfo["user"] + ":" + logInfo["password"] +
"@(localhost)/" + logInfo["database"] + "?charset=utf8mb4&parseTime=True&loc=Local"
DB, err = gorm.Open(mysql.Open(sqlInfo), &gorm.Config{})
if err != nil {
logrus.Panic(err)
}
}
// Backcheck content through link
func findlink(name string) string {
var p Users
err := DB.First(&p, "Route = ?", name)
if err != nil {
logrus.Error(err)
}
return p.Name
}
// save text information
func savetext(_username string, s string, t1 time.Time) {
p := Users{
Username: _username,
Name: s,
Date: time.Now(),
Time1: t1,
}
DB.Create(&p)
p1 := content{
Name: s,
Time: 0,
}
DB.Create(&p1)
}
// Check whether the number of visits exceeds the threshold
func checkt(s string) {
var p content
err := DB.First(&p, "Route = ?", s)
if err != nil {
logrus.Error(err)
}
p.Time++
if p.Time > 200 {
DB.Delete(&p)
}
}
// Check whether the number of visits exceeds the time limit
func checkt1(s string) {
var p []Users
DB.Find(&p)
for i := 0; i < len(p); i++ {
t := time.Now()
if p[i].Time1.After(t) {
DB.Delete(&p)
}
}
}
package model
import (
"time"
"gorm.io/gorm"
)
type Users struct {
gorm.Model
Username string
Passwd string
Name string
Date time.Time
Size uint
Route string
Time1 time.Time
}
type content struct {
gorm.Model
Name string
Time uint
}
\ No newline at end of file
package utils
import (
"sync"
"github.com/go-playground/validator/v10"
)
type CustomValidator struct {
once sync.Once
validate *validator.Validate
}
func (c *CustomValidator) Validate(i interface{}) error {
c.lazyInit()
return c.validate.Struct(i)
}
func (c *CustomValidator) lazyInit() {
c.once.Do(func() {
c.validate = validator.New()
})
}
返回链接
\ No newline at end of file
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