diff --git a/README.md b/.github/rE35T/README.md similarity index 100% rename from README.md rename to .github/rE35T/README.md diff --git a/.github/rE35T/auth.go b/.github/rE35T/auth.go new file mode 100644 index 0000000..b947cd2 --- /dev/null +++ b/.github/rE35T/auth.go @@ -0,0 +1,97 @@ +package main + +import ( + "encoding/base64" + "github.com/gin-gonic/gin" + "gorm.io/gorm" + "log" + "math/rand" + "net/http" +) + +// 用户结构体 +type User struct { + gorm.Model + Profile Profile // 与 Profile 一对一关联 + Blogs []Blog `gorm:"foreignKey:UserId"` // 与 Blog 一对多关联 + Replies []Reply `gorm:"foreignKey:UserId"` // 与 Reply 一对多关联 + + ID uint // 用户ID + Username string `json:"username"` // 用户名 + Password string `json:"password"` // 密码 +} + +// 登录功能 +func login(c *gin.Context) { + var user User + + // 解析 JSON 请求 + if err := c.ShouldBindJSON(&user); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) // 返回错误信息 + return + } + + // 确认用户是否存在并且密码是否正确 + UserExists := checkUserExists(user.Username, user.Password) + if UserExists { + c.JSON(http.StatusOK, gin.H{"message": "登陆成功!"}) // 登录成功 + c.SetCookie("username", base64.StdEncoding.EncodeToString([]byte(user.Username)), 3600, "/", "localhost", false, true) // 设置 Cookie + log.Println("Cookie set:", base64.StdEncoding.EncodeToString([]byte(user.Username))) + user.ID = uint(rand.Uint32()) // 随机生成用户ID(此处可能需要修改) + return + } else { + c.JSON(http.StatusOK, gin.H{"message": "用户未注册,请先注册!"}) // 用户未注册 + } +} + +// 注册功能 +func register(c *gin.Context) { + var user User + if err := c.ShouldBindJSON(&user); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) // 返回错误信息 + return + } + + // 检查用户是否已注册 + UserExists := checkUserExists(user.Username, user.Password) + exists := checkUsernameExists(user.Username) + if UserExists { + c.JSON(http.StatusOK, gin.H{"message": "该账户已注册,请转至登陆界面"}) // 已注册提示 + return + } + if exists { + c.JSON(http.StatusOK, gin.H{"message": "该用户名已存在,请更换"}) // 用户名已存在 + } else { + // 创建用户记录 + if err := db.Create(&user).Error; err != nil { + log.Println("Error creating user:", err) // 打印错误 + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) // 返回错误信息 + return + } + c.JSON(http.StatusCreated, gin.H{"message": "成功注册!"}) // 注册成功 + } +} + +// 检查用户是否存在 +func checkUserExists(username string, password string) bool { + var user User + result := db.Where("username = ?", username).First(&user) // 查询用户 + if result.Error != nil { + log.Println("Error checking user existence:", result.Error) // 打印错误 + return false + } + + // 返回用户名和密码是否匹配 + return user.Username == username && user.Password == password +} + +// 检查用户名是否已存在 +func checkUsernameExists(username string) bool { + var user User + result := db.Where("username = ?", username).First(&user) // 查询用户 + if result.Error != nil { + log.Println("Error checking user existence:", result.Error) // 打印错误 + return false + } + return user.Username == username +} diff --git a/.github/rE35T/blog.go b/.github/rE35T/blog.go new file mode 100644 index 0000000..e10fe88 --- /dev/null +++ b/.github/rE35T/blog.go @@ -0,0 +1,184 @@ +package main + +import ( + "encoding/base64" + "fmt" + "github.com/gin-gonic/gin" + "gorm.io/gorm" + "math/rand" + "net/http" + "time" +) + +type Blog struct { + gorm.Model + //User + UserId uint + //一对多reply + Replies []Reply `gorm:"foreignKey:BlogID"` + + ID uint + Time string + Content string `json:"content"` + Title string `json:"title"` + Author string `json:"author"` + Type string `json:"type"` +} + +type Reply struct { + gorm.Model + //User + UserId uint + //blog + BlogID uint `json:"BlogID"` + Body string `json:"body"` + Who string `json:"who"` +} + +// 显示我的提问与回复 +func mine(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + //查找user下的所有blog和blog下的所有reply + var user User + // 先通过 username 查询 User + if err := db.Where("username = ?", userId).First(&user).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + // 通过预加载获取该用户的所有 Blogs 和对应的 Replies + if err := db.Preload("Blogs.Replies").First(&user, user.ID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Blogs not found"}) + return + } + c.JSON(http.StatusOK, gin.H{"user": user}) + return + +} + +// 显示其他人的问题 +func others(c *gin.Context) { + var blogs []Blog + // 预加载所有 Blogs 及其对应的 Replies + if err := db.Preload("Replies").Find(&blogs).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve blogs"}) + return + } + c.JSON(http.StatusOK, gin.H{"blogs": blogs}) + return +} + +// 创建我的新问题 +func mineNews(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + var blogs Blog + blogs.ID = uint(rand.Uint32()) + blogs.Time = time.Now().Format("2006-01-02 15:04:05") + if err := c.ShouldBind(&blogs); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + var user User + if err := db.Where("username = ?", string(userId)).First(&user).Error; err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + //键赋值 + blogs.UserId = user.ID + + if err := db.Create(&blogs).Error; err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + c.JSON(http.StatusOK, gin.H{"blogs": blogs}) + fmt.Println("成功发布问题") +} + +func reply(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + } + + // 检查用户是否存在 + var user User + if err := db.Where("username = ?", userId).First(&user).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + //创建回复 + var reply Reply + if err := c.ShouldBind(&reply); err != nil { + + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + //键赋值 + reply.UserId = user.ID + //上传回复 + if err := db.Create(&reply).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create reply"}) + } + c.JSON(http.StatusOK, gin.H{"reply": reply}) +} + +func blogEdit(c *gin.Context) { + + var blog Blog + blogID := c.Param("id") // 获取 URL 中的博客 ID + + // 查找博客 + if err := db.First(&blog, blogID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Blog not found"}) + return + } + + // 绑定更新数据 + if err := c.ShouldBind(&blog); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // 更新博客 + if err := db.Save(&blog).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update blog"}) + return + } + + c.JSON(http.StatusOK, gin.H{"blog": blog}) +} + +func blogDelete(c *gin.Context) { + + blogID := c.Param("id") // 获取 URL 中的博客 ID + var blog Blog + + // 查找博客 + if err := db.First(&blog, blogID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Blog not found"}) + return + } + + // 删除博客 + if err := db.Delete(&blog).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete blog"}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Blog deleted successfully"}) +} diff --git a/.github/rE35T/go.mod b/.github/rE35T/go.mod new file mode 100644 index 0000000..858fbc3 --- /dev/null +++ b/.github/rE35T/go.mod @@ -0,0 +1,39 @@ +module myproject + +go 1.23.1 + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/bytedance/sonic v1.12.3 // indirect + github.com/bytedance/sonic/loader v0.2.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.5 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.10.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.22.1 // indirect + github.com/go-sql-driver/mysql v1.8.1 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.8 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.10.0 // indirect + golang.org/x/crypto v0.27.0 // indirect + golang.org/x/net v0.29.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + gorm.io/driver/mysql v1.5.7 // indirect + gorm.io/gorm v1.25.12 // indirect +) diff --git a/.github/rE35T/go.sum b/.github/rE35T/go.sum new file mode 100644 index 0000000..e85c7fe --- /dev/null +++ b/.github/rE35T/go.sum @@ -0,0 +1,91 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/bytedance/sonic v1.12.3 h1:W2MGa7RCU1QTeYRTPE3+88mVC0yXmsRQRChiyVocVjU= +github.com/bytedance/sonic v1.12.3/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM= +github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4= +github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA= +github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM= +github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= +golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= +golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= +gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= +gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= +gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/.github/rE35T/main.go b/.github/rE35T/main.go new file mode 100644 index 0000000..7f95859 --- /dev/null +++ b/.github/rE35T/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" + "gorm.io/driver/mysql" + "gorm.io/gorm" + "log" +) + +// 数据库连接变量 +var db *gorm.DB + +func main() { + // 创建 Gin 引擎 + r := gin.Default() + + // 定义主页面的路由 + r.GET("/", func(c *gin.Context) { + // 主页面处理逻辑 + }) + + // 认证相关的路由 + a := r.Group("/auth") + { + a.POST("/login", login) // 用户登录 + a.POST("/register", register) // 用户注册 + } + + // 博客相关的路由 + b := r.Group("/blog") + { + b.GET("/mine", mine) // 查看我的提问和回复 + b.GET("/others", others) // 查看其他人的提问 + b.POST("/others/reply", reply) // 回复其他人的提问 + b.POST("/mine/new", mineNews) // 发布新的提问 + b.PUT("/mine/edit", blogEdit) // 编辑我的提问 + b.DELETE("/others/reply/delete", blogDelete) // 删除回复 + } + + // 个人资料相关的路由 + c := r.Group("/profile") + { + c.GET("/myself", myself) // 查看我的个人资料 + c.POST("/myself/createProfile", createProfile) // 创建个人资料 + c.PUT("/myself/edit", edit) // 编辑个人资料 + c.DELETE("/myself/delete", profileDelete) // 删除个人资料 + } + + // 初始化数据库连接 + initDB() + + // 自动迁移数据库表 + if err := db.AutoMigrate(&User{}, &Profile{}, &Blog{}, &Reply{}); err != nil { + fmt.Println("迁移错误:", err) // 打印错误信息 + } + + // 启动服务器 + r.Run(":9090") +} + +// 链接数据库函数 +func initDB() { + // 数据库连接字符串 + dsn := "root:35798@tcp(127.0.0.1:3306)/hduhelp?charset=utf8mb4&parseTime=True&loc=Local" + var err error + // 打开数据库连接 + db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) + if err != nil { + log.Fatal("Failed to connect to the database:", err) // 打印连接错误 + } + log.Println("Connected to the database successfully.") // 连接成功的日志 +} diff --git a/.github/rE35T/myproject.exe b/.github/rE35T/myproject.exe new file mode 100644 index 0000000..de77044 Binary files /dev/null and b/.github/rE35T/myproject.exe differ diff --git a/.github/rE35T/profile.go b/.github/rE35T/profile.go new file mode 100644 index 0000000..e97ca78 --- /dev/null +++ b/.github/rE35T/profile.go @@ -0,0 +1,175 @@ +package main + +import ( + "encoding/base64" + "fmt" + "github.com/gin-gonic/gin" + "gorm.io/gorm" + "log" + "net/http" +) + +type Profile struct { + gorm.Model + //从属于user + UserId uint + //profile内容 + Name string `json:"name"` + Age int `json:"age"` + Gender string `json:"gender"` + PhoneNumber string `json:"phoneNumber"` + Email string `json:"email"` + Hobbies string `json:"hobbies"` +} + +func loadCookie(c *gin.Context) (string, error) { + + UserId, err := c.Cookie("username") + log.Println(UserId) + if err != nil { + return "", fmt.Errorf("unauthorized") + } + return UserId, nil + +} + +//func uploadProfile(c *gin.Context, userId string) error { +// file, err := c.FormFile("selfie") +// if err != nil { +// return fmt.Errorf("invalid file") +// } +// +// // 验证文件类型 +// if file.Header.Get("Content-Type") != "image/jpeg" { +// return fmt.Errorf("only JPEG files are allowed") +// } +// +// // 设置保存路径 +// savePath := "./uploads/" + userId + "_selfie.jpg" // 根据用户 ID 保存文件 +// +// // 保存文件 +// if err := c.SaveUploadedFile(file, savePath); err != nil { +// return fmt.Errorf("failed to save file") +// } +// +// // 更新用户个人资料 +// var profile Profile +// if err := db.Where("username = ?", userId).First(&profile).Error; err == nil { +// profile.Selfie = savePath // 更新 Selfie 字段为文件路径 +// db.Save(&profile) // 保存到数据库 +// } +// +// return nil +//} + +func createProfile(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + var profile Profile + if err := c.ShouldBindJSON(&profile); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"}) + return + } + // 检查用户是否存在 + var user User + if err := db.Where("username = ?", userId).First(&user).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + // 创建个人资料 + profile.Name = string(userId) // 确保设置用户名 + if err := db.Create(&profile).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create profile"}) + return + } + + //// 上传头像 + //if err := uploadProfile(c, string(userId)); err != nil { + // c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + // return + //} + + c.JSON(http.StatusOK, gin.H{"message": "Profile created successfully", "profile": profile}) +} + +func myself(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, err := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + //向数据库查询 + var profile Profile + if err := db.Where("name = ?", userId).First(&profile).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve profile"}) + return + } else { + c.JSON(http.StatusOK, gin.H{"message": "Successfully retrieved profile", "profile": profile}) + } + +} +func edit(c *gin.Context) { + cookieValue, err := loadCookie(c) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + userIdBytes, _ := base64.StdEncoding.DecodeString(cookieValue) + userId := string(userIdBytes) // 将字节转换为字符串 + + var profile Profile + if err := c.ShouldBindJSON(&profile); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"}) + return + } + + // 检查用户是否存在 + var user User + if err := db.Where("username = ?", userId).First(&user).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + // 查找对应的个人资料 + var existingProfile Profile + if err := db.Where("name = ?", user.Username).First(&existingProfile).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Profile not found"}) + return + } + + // 更新个人资料字段 + existingProfile.Name = profile.Name + existingProfile.Age = profile.Age + existingProfile.Gender = profile.Gender + existingProfile.PhoneNumber = profile.PhoneNumber + existingProfile.Email = profile.Email + existingProfile.Hobbies = profile.Hobbies + + // 保存更新 + if err := db.Save(&existingProfile).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update profile"}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Profile updated successfully", "profile": existingProfile}) +} + +func profileDelete(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + log.Println(userId) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + db.Delete(&Profile{}, "name = ?", string(userId)) +} diff --git a/rE35T/README.md b/rE35T/README.md new file mode 100644 index 0000000..724ff4d --- /dev/null +++ b/rE35T/README.md @@ -0,0 +1,10 @@ +# backend_2024_freshman_task + +2024 杭助后端招新小任务提交仓库 + +- fork本仓库 +- git clone 你 fork 出来的仓库 +- 在仓库根目录下新建一个和你 github 用户名同名的文件夹 +- 在此文件夹内,放入你的代码 +- 提交 Pull request +- github action通过后,即为提交成功 \ No newline at end of file diff --git a/rE35T/auth.go b/rE35T/auth.go new file mode 100644 index 0000000..b947cd2 --- /dev/null +++ b/rE35T/auth.go @@ -0,0 +1,97 @@ +package main + +import ( + "encoding/base64" + "github.com/gin-gonic/gin" + "gorm.io/gorm" + "log" + "math/rand" + "net/http" +) + +// 用户结构体 +type User struct { + gorm.Model + Profile Profile // 与 Profile 一对一关联 + Blogs []Blog `gorm:"foreignKey:UserId"` // 与 Blog 一对多关联 + Replies []Reply `gorm:"foreignKey:UserId"` // 与 Reply 一对多关联 + + ID uint // 用户ID + Username string `json:"username"` // 用户名 + Password string `json:"password"` // 密码 +} + +// 登录功能 +func login(c *gin.Context) { + var user User + + // 解析 JSON 请求 + if err := c.ShouldBindJSON(&user); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) // 返回错误信息 + return + } + + // 确认用户是否存在并且密码是否正确 + UserExists := checkUserExists(user.Username, user.Password) + if UserExists { + c.JSON(http.StatusOK, gin.H{"message": "登陆成功!"}) // 登录成功 + c.SetCookie("username", base64.StdEncoding.EncodeToString([]byte(user.Username)), 3600, "/", "localhost", false, true) // 设置 Cookie + log.Println("Cookie set:", base64.StdEncoding.EncodeToString([]byte(user.Username))) + user.ID = uint(rand.Uint32()) // 随机生成用户ID(此处可能需要修改) + return + } else { + c.JSON(http.StatusOK, gin.H{"message": "用户未注册,请先注册!"}) // 用户未注册 + } +} + +// 注册功能 +func register(c *gin.Context) { + var user User + if err := c.ShouldBindJSON(&user); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) // 返回错误信息 + return + } + + // 检查用户是否已注册 + UserExists := checkUserExists(user.Username, user.Password) + exists := checkUsernameExists(user.Username) + if UserExists { + c.JSON(http.StatusOK, gin.H{"message": "该账户已注册,请转至登陆界面"}) // 已注册提示 + return + } + if exists { + c.JSON(http.StatusOK, gin.H{"message": "该用户名已存在,请更换"}) // 用户名已存在 + } else { + // 创建用户记录 + if err := db.Create(&user).Error; err != nil { + log.Println("Error creating user:", err) // 打印错误 + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) // 返回错误信息 + return + } + c.JSON(http.StatusCreated, gin.H{"message": "成功注册!"}) // 注册成功 + } +} + +// 检查用户是否存在 +func checkUserExists(username string, password string) bool { + var user User + result := db.Where("username = ?", username).First(&user) // 查询用户 + if result.Error != nil { + log.Println("Error checking user existence:", result.Error) // 打印错误 + return false + } + + // 返回用户名和密码是否匹配 + return user.Username == username && user.Password == password +} + +// 检查用户名是否已存在 +func checkUsernameExists(username string) bool { + var user User + result := db.Where("username = ?", username).First(&user) // 查询用户 + if result.Error != nil { + log.Println("Error checking user existence:", result.Error) // 打印错误 + return false + } + return user.Username == username +} diff --git a/rE35T/blog.go b/rE35T/blog.go new file mode 100644 index 0000000..e10fe88 --- /dev/null +++ b/rE35T/blog.go @@ -0,0 +1,184 @@ +package main + +import ( + "encoding/base64" + "fmt" + "github.com/gin-gonic/gin" + "gorm.io/gorm" + "math/rand" + "net/http" + "time" +) + +type Blog struct { + gorm.Model + //User + UserId uint + //一对多reply + Replies []Reply `gorm:"foreignKey:BlogID"` + + ID uint + Time string + Content string `json:"content"` + Title string `json:"title"` + Author string `json:"author"` + Type string `json:"type"` +} + +type Reply struct { + gorm.Model + //User + UserId uint + //blog + BlogID uint `json:"BlogID"` + Body string `json:"body"` + Who string `json:"who"` +} + +// 显示我的提问与回复 +func mine(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + //查找user下的所有blog和blog下的所有reply + var user User + // 先通过 username 查询 User + if err := db.Where("username = ?", userId).First(&user).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + // 通过预加载获取该用户的所有 Blogs 和对应的 Replies + if err := db.Preload("Blogs.Replies").First(&user, user.ID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Blogs not found"}) + return + } + c.JSON(http.StatusOK, gin.H{"user": user}) + return + +} + +// 显示其他人的问题 +func others(c *gin.Context) { + var blogs []Blog + // 预加载所有 Blogs 及其对应的 Replies + if err := db.Preload("Replies").Find(&blogs).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve blogs"}) + return + } + c.JSON(http.StatusOK, gin.H{"blogs": blogs}) + return +} + +// 创建我的新问题 +func mineNews(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + var blogs Blog + blogs.ID = uint(rand.Uint32()) + blogs.Time = time.Now().Format("2006-01-02 15:04:05") + if err := c.ShouldBind(&blogs); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + var user User + if err := db.Where("username = ?", string(userId)).First(&user).Error; err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + //键赋值 + blogs.UserId = user.ID + + if err := db.Create(&blogs).Error; err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + c.JSON(http.StatusOK, gin.H{"blogs": blogs}) + fmt.Println("成功发布问题") +} + +func reply(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + } + + // 检查用户是否存在 + var user User + if err := db.Where("username = ?", userId).First(&user).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + //创建回复 + var reply Reply + if err := c.ShouldBind(&reply); err != nil { + + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } + + //键赋值 + reply.UserId = user.ID + //上传回复 + if err := db.Create(&reply).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create reply"}) + } + c.JSON(http.StatusOK, gin.H{"reply": reply}) +} + +func blogEdit(c *gin.Context) { + + var blog Blog + blogID := c.Param("id") // 获取 URL 中的博客 ID + + // 查找博客 + if err := db.First(&blog, blogID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Blog not found"}) + return + } + + // 绑定更新数据 + if err := c.ShouldBind(&blog); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // 更新博客 + if err := db.Save(&blog).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update blog"}) + return + } + + c.JSON(http.StatusOK, gin.H{"blog": blog}) +} + +func blogDelete(c *gin.Context) { + + blogID := c.Param("id") // 获取 URL 中的博客 ID + var blog Blog + + // 查找博客 + if err := db.First(&blog, blogID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Blog not found"}) + return + } + + // 删除博客 + if err := db.Delete(&blog).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete blog"}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Blog deleted successfully"}) +} diff --git a/rE35T/go.mod b/rE35T/go.mod new file mode 100644 index 0000000..858fbc3 --- /dev/null +++ b/rE35T/go.mod @@ -0,0 +1,39 @@ +module myproject + +go 1.23.1 + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/bytedance/sonic v1.12.3 // indirect + github.com/bytedance/sonic/loader v0.2.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.5 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.10.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.22.1 // indirect + github.com/go-sql-driver/mysql v1.8.1 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.8 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.10.0 // indirect + golang.org/x/crypto v0.27.0 // indirect + golang.org/x/net v0.29.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + gorm.io/driver/mysql v1.5.7 // indirect + gorm.io/gorm v1.25.12 // indirect +) diff --git a/rE35T/go.sum b/rE35T/go.sum new file mode 100644 index 0000000..e85c7fe --- /dev/null +++ b/rE35T/go.sum @@ -0,0 +1,91 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/bytedance/sonic v1.12.3 h1:W2MGa7RCU1QTeYRTPE3+88mVC0yXmsRQRChiyVocVjU= +github.com/bytedance/sonic v1.12.3/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM= +github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4= +github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA= +github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM= +github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= +golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= +golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= +gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= +gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= +gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/rE35T/main.go b/rE35T/main.go new file mode 100644 index 0000000..7f95859 --- /dev/null +++ b/rE35T/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" + "gorm.io/driver/mysql" + "gorm.io/gorm" + "log" +) + +// 数据库连接变量 +var db *gorm.DB + +func main() { + // 创建 Gin 引擎 + r := gin.Default() + + // 定义主页面的路由 + r.GET("/", func(c *gin.Context) { + // 主页面处理逻辑 + }) + + // 认证相关的路由 + a := r.Group("/auth") + { + a.POST("/login", login) // 用户登录 + a.POST("/register", register) // 用户注册 + } + + // 博客相关的路由 + b := r.Group("/blog") + { + b.GET("/mine", mine) // 查看我的提问和回复 + b.GET("/others", others) // 查看其他人的提问 + b.POST("/others/reply", reply) // 回复其他人的提问 + b.POST("/mine/new", mineNews) // 发布新的提问 + b.PUT("/mine/edit", blogEdit) // 编辑我的提问 + b.DELETE("/others/reply/delete", blogDelete) // 删除回复 + } + + // 个人资料相关的路由 + c := r.Group("/profile") + { + c.GET("/myself", myself) // 查看我的个人资料 + c.POST("/myself/createProfile", createProfile) // 创建个人资料 + c.PUT("/myself/edit", edit) // 编辑个人资料 + c.DELETE("/myself/delete", profileDelete) // 删除个人资料 + } + + // 初始化数据库连接 + initDB() + + // 自动迁移数据库表 + if err := db.AutoMigrate(&User{}, &Profile{}, &Blog{}, &Reply{}); err != nil { + fmt.Println("迁移错误:", err) // 打印错误信息 + } + + // 启动服务器 + r.Run(":9090") +} + +// 链接数据库函数 +func initDB() { + // 数据库连接字符串 + dsn := "root:35798@tcp(127.0.0.1:3306)/hduhelp?charset=utf8mb4&parseTime=True&loc=Local" + var err error + // 打开数据库连接 + db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) + if err != nil { + log.Fatal("Failed to connect to the database:", err) // 打印连接错误 + } + log.Println("Connected to the database successfully.") // 连接成功的日志 +} diff --git a/rE35T/myproject.exe b/rE35T/myproject.exe new file mode 100644 index 0000000..de77044 Binary files /dev/null and b/rE35T/myproject.exe differ diff --git a/rE35T/profile.go b/rE35T/profile.go new file mode 100644 index 0000000..e97ca78 --- /dev/null +++ b/rE35T/profile.go @@ -0,0 +1,175 @@ +package main + +import ( + "encoding/base64" + "fmt" + "github.com/gin-gonic/gin" + "gorm.io/gorm" + "log" + "net/http" +) + +type Profile struct { + gorm.Model + //从属于user + UserId uint + //profile内容 + Name string `json:"name"` + Age int `json:"age"` + Gender string `json:"gender"` + PhoneNumber string `json:"phoneNumber"` + Email string `json:"email"` + Hobbies string `json:"hobbies"` +} + +func loadCookie(c *gin.Context) (string, error) { + + UserId, err := c.Cookie("username") + log.Println(UserId) + if err != nil { + return "", fmt.Errorf("unauthorized") + } + return UserId, nil + +} + +//func uploadProfile(c *gin.Context, userId string) error { +// file, err := c.FormFile("selfie") +// if err != nil { +// return fmt.Errorf("invalid file") +// } +// +// // 验证文件类型 +// if file.Header.Get("Content-Type") != "image/jpeg" { +// return fmt.Errorf("only JPEG files are allowed") +// } +// +// // 设置保存路径 +// savePath := "./uploads/" + userId + "_selfie.jpg" // 根据用户 ID 保存文件 +// +// // 保存文件 +// if err := c.SaveUploadedFile(file, savePath); err != nil { +// return fmt.Errorf("failed to save file") +// } +// +// // 更新用户个人资料 +// var profile Profile +// if err := db.Where("username = ?", userId).First(&profile).Error; err == nil { +// profile.Selfie = savePath // 更新 Selfie 字段为文件路径 +// db.Save(&profile) // 保存到数据库 +// } +// +// return nil +//} + +func createProfile(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + var profile Profile + if err := c.ShouldBindJSON(&profile); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"}) + return + } + // 检查用户是否存在 + var user User + if err := db.Where("username = ?", userId).First(&user).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + // 创建个人资料 + profile.Name = string(userId) // 确保设置用户名 + if err := db.Create(&profile).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create profile"}) + return + } + + //// 上传头像 + //if err := uploadProfile(c, string(userId)); err != nil { + // c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + // return + //} + + c.JSON(http.StatusOK, gin.H{"message": "Profile created successfully", "profile": profile}) +} + +func myself(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, err := base64.StdEncoding.DecodeString(cookieValue) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + //向数据库查询 + var profile Profile + if err := db.Where("name = ?", userId).First(&profile).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve profile"}) + return + } else { + c.JSON(http.StatusOK, gin.H{"message": "Successfully retrieved profile", "profile": profile}) + } + +} +func edit(c *gin.Context) { + cookieValue, err := loadCookie(c) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + userIdBytes, _ := base64.StdEncoding.DecodeString(cookieValue) + userId := string(userIdBytes) // 将字节转换为字符串 + + var profile Profile + if err := c.ShouldBindJSON(&profile); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"}) + return + } + + // 检查用户是否存在 + var user User + if err := db.Where("username = ?", userId).First(&user).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + // 查找对应的个人资料 + var existingProfile Profile + if err := db.Where("name = ?", user.Username).First(&existingProfile).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "Profile not found"}) + return + } + + // 更新个人资料字段 + existingProfile.Name = profile.Name + existingProfile.Age = profile.Age + existingProfile.Gender = profile.Gender + existingProfile.PhoneNumber = profile.PhoneNumber + existingProfile.Email = profile.Email + existingProfile.Hobbies = profile.Hobbies + + // 保存更新 + if err := db.Save(&existingProfile).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update profile"}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Profile updated successfully", "profile": existingProfile}) +} + +func profileDelete(c *gin.Context) { + cookieValue, err := loadCookie(c) + userId, _ := base64.StdEncoding.DecodeString(cookieValue) + log.Println(userId) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + db.Delete(&Profile{}, "name = ?", string(userId)) +}