diff --git a/database.go b/database.go new file mode 100644 index 0000000..736c8eb --- /dev/null +++ b/database.go @@ -0,0 +1,47 @@ +package main + +import ( + "golang.org/x/crypto/bcrypt" + "gorm.io/driver/mysql" + "gorm.io/gorm" + "gorm.io/gorm/logger" + "log" +) + +var db *gorm.DB + +// 初始化数据库 +func inDB() { + var err error + //数据库mysql连接信息 + dsn := "root:ZJHZjn20060629@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local" + db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{ + Logger: logger.Default.LogMode(logger.Info), + }) + //进行连接测试 + if err != nil { + log.Fatal("数据库连接失败: %v", err) + } + //自动迁移与创建用户表 + if err := db.AutoMigrate(&User{}); err != nil { + log.Fatal("迁移数据库错误: %v", err) + } + if err := db.AutoMigrate(&Question{}); err != nil { + log.Fatal("迁移数据库错误: %v", err) + } + if err := db.AutoMigrate(&Answer{}); err != nil { + log.Fatal("迁移数据库错误: %v", err) + } + //fmt.Println("用户表创立成功") +} + +// 加密,哈希保护用户密码和验证 +func savepassword(password string) (string, error) { + sec, err := bcrypt.GenerateFromPassword([]byte(password), 14) + return string(sec), err +} + +func checkpassword(password, hash string) bool { + err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) + return err != nil +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..cdd77fa --- /dev/null +++ b/go.mod @@ -0,0 +1,40 @@ +module newtest + +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/dgrijalva/jwt-go v3.2.0+incompatible // 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/go.sum b/go.sum new file mode 100644 index 0000000..f345034 --- /dev/null +++ b/go.sum @@ -0,0 +1,57 @@ +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +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/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +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/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +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/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +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/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +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/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/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +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/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +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/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +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/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +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/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +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/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= diff --git a/main.go b/main.go new file mode 100644 index 0000000..9860a12 --- /dev/null +++ b/main.go @@ -0,0 +1,312 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" + "net/http" + "time" +) + +// user数据模型 +type User struct { + ID uint `json:"id" gorm:"primarykey"` + Username string `json:"username" gorm:"unique"` + Password string `json:"password"` + Email string `json:"email"` +} + +// Question 建立提问平台结构 +type Question struct { + ID uint `json:"question_id" gorm:"primarykey"` + Title string `json:"title"` + Content string `json:"content"` + UserID uint `json:"user_id"` + CreatedAt time.Time `json:"created_at"` +} + +// Answer 数据模型 +type Answer struct { + ID uint `json:"id" gorm:"primarykey"` + Content string `json:"content"` + QuestionID uint `json:"question_id"` // 关联问题的ID + UserID uint `json:"user_id"` // 关联用户的ID + CreatedAt time.Time `json:"created_at"` +} + +// CreateQuestion 创建问题 +func CreateQuestion(c *gin.Context) { + var question Question + if err := c.ShouldBind(&question); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "输入错误!"}) + return + } + question.CreatedAt = time.Now() + + result := db.Create(&question) + if result.Error != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "问题创建失败!"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "问题创建成功!", "question": question}) +} + +// AuthMiddleware 认证中间件 +func AuthMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + // 这里不需要获取 UserID,登录时已设置 + c.Next() + } +} + +// GetQuestion 获取问题列表 +func GetQuestion(c *gin.Context) { + //创立问题列表 + var question []Question + if err := db.Find(&question).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "问题获取失败!"}) + return + } + c.JSON(http.StatusOK, gin.H{"questions": question}) +} + +// SingelQuestion 获取单个问题 +func SingelQuestion(c *gin.Context) { + var question Question + id := c.Param("id") + if err := db.First(&question, id).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "问题未找到!"}) + return + } + c.JSON(http.StatusOK, question) +} + +// PutQuestion 更新问题 +func PutQuestion(c *gin.Context) { + var question Question + id := c.Param("id") + + if err := db.First(&question, id).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "问题未找到!"}) + return + } + if err := c.ShouldBindJSON(&question); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "错误输入!"}) + return + } + db.Save(&question) + c.JSON(http.StatusOK, gin.H{"message": "问题更新成功!"}) +} + +// DeleteQuestion 删除问题 +func DeleteQuestion(c *gin.Context) { + var question Question + id := c.Param("id") + if err := db.Delete(&question, id).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "问题未找到"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "问题删除成功!"}) +} + +// CreateAnswer 创建答案 +func CreateAnswer(c *gin.Context) { + var answer Answer + if err := c.ShouldBind(&answer); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "输入错误!"}) + return + } + answer.CreatedAt = time.Now() + result := db.Create(&answer) + if result.Error != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "答案创建失败!"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "答案创建成功!", "answer": answer}) +} + +// GetAnswers 获取某个问题的所有答案 +func GetAnswers(c *gin.Context) { + questionID := c.Param("question_id") + var answers []Answer + + //查询answers + if err := db.Where("question_id = ?", questionID).Find(&answers).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "答案获取失败!"}) + return + } + + //返回答案列表 + c.JSON(http.StatusOK, gin.H{"answers": answers}) +} + +// UpdateAnswer 更新答案 +func UpdateAnswer(c *gin.Context) { + var answer Answer + id := c.Param("id") + + if err := db.First(&answer, id).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "答案未找到!"}) + return + } + + if err := c.ShouldBindJSON(&answer); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "错误输入!"}) + return + } + + db.Save(&answer) + c.JSON(http.StatusOK, gin.H{"message": "答案更新成功!"}) +} + +// DeleteAnswer 删除答案 +func DeleteAnswer(c *gin.Context) { + var answer Answer + id := c.Param("id") + + if err := db.Delete(&answer, id).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "答案未找到!"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "答案删除成功!"}) +} + +func main() { + inDB() + //创建路由 + r := gin.Default() + //用户注册API,通过JSON格式提交信息 + r.POST("/register", func(c *gin.Context) { + var user User + if err := c.ShouldBind(&user); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "错误输入"}) + return + } + + //加密保护用户密码信息 + hashPassword, err := savepassword(user.Password) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "加密失败!"}) + return + } + user.Password = hashPassword + fmt.Printf("Storing user with hashed password: %s\n", user.Password) + //保存用户信息 + result := db.Create(&user) + if result.Error != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "注册失败!"}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "注册成功!"}) + }) + + //用户登录API + r.POST("/login", func(c *gin.Context) { + var input User + if err := c.ShouldBind(&input); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "错误输入!"}) + return + } + + //fmt.Printf("Login attempt - Username: %s, Password: %s\n", input.Username, input.Password) + + var user User + //用户查找 + if err := db.Where("username = ?", input.Username).First(&user).Error; err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "用户无法找到!"}) + return + } + //fmt.Println(user.Username, user.Password) + //验证用户密码 + if !checkpassword(input.Password, user.Password) { + c.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误!"}) + return + } + c.Set("UserID", user.ID) + fmt.Println("UserID set in context:", user.ID) // 调试日志 + //fmt.Println("UserID:", user.ID) + c.JSON(http.StatusOK, gin.H{"message": "登录成功!", "user_id": user.ID}) + }) + + //查看用户个人信息API + r.GET("/user/:id", func(c *gin.Context) { + var user User + id := c.Param("id") + + if err := db.First(&user, id).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "用户未找到!"}) + return + } + //不返回用户密码 + user.Password = "" + c.JSON(http.StatusOK, user) + }) + //修改用户信息API + r.PUT("/user/:id", func(c *gin.Context) { + var input User + id := c.Param("id") + + //查找用户信息 + if err := db.First(&input, id).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "用户未找到!"}) + return + } + + //创建临时结构体,用来实现只绑定需要更新的片段,防止ID被修改 + type UpdateUserInput struct { + Username string `json:"username,omitempty"` + Email string `json:"email,omitempty"` + } + var updateInput UpdateUserInput + if err := c.ShouldBind(&updateInput); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "错误输入!"}) + return + } + + //更新用户信息 + if updateInput.Username != "" { + input.Username = updateInput.Username + } + if updateInput.Email != "" { + input.Email = updateInput.Email + } + if err := db.Save(&input).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败!"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "更新成功!"}) + }) + + // 创建问题API + r.POST("/questions", CreateQuestion) + + // 获取问题列表API + r.GET("/questions", GetQuestion) + + // 查看单个问题API + r.GET("/questions/:question_id", SingelQuestion) + + // 更新问题API + r.PUT("/questions/:question_id", PutQuestion) + + // 删除问题API + r.DELETE("/questions/:question_id", DeleteQuestion) + + // 创建答案API + r.POST("/questions/:question_id/answers", CreateAnswer) + + // 获取某个问题的所有答案API + r.GET("/questions/:question_id/answers", GetAnswers) + + // 更新答案API + r.PUT("/answers/:id", UpdateAnswer) + + // 删除答案API + r.DELETE("/answers/:id", DeleteAnswer) + + r.Run(":8080") + /*测试数据库连接 + fmt.Println("顺利连接!") + 还未完成,继续接入AI*/ + +}