Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: finish task #3

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions 007WS-cry/auth_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package main

import(
"database/sql"
"net/http"

"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)

var sessionMap = make(map[string]*User)

type User struct {
ID int
Username string
Password string
}

func registerHandler(db *sql.DB) gin.HandlerFunc {
return func(c *gin.Context) {

var req struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}

if err := c.ShouldBindWith(&req, binding.JSON); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
return
}

// TODO: 检查用户名是否已存在
var existingUser User
err := db.QueryRow("SELECT id FROM users WHERE username = ?", req.Username).Scan(&existingUser.ID)
if err == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "用户名已存在"})
return
}

// TODO: 创建新用户
_, err = db.Exec("INSERT INTO users (username, password) VALUES (?, ?)", req.Username, req.Password)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "创建用户失败"})
return
}

c.JSON(http.StatusOK, gin.H{"message": "用户创建成功"})
}
}

func loginHandler(db *sql.DB) gin.HandlerFunc {
return func(c *gin.Context) {

var req struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}

if err := c.ShouldBindWith(&req, binding.JSON); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
return
}

// TODO: 验证用户名和密码
var user User
err := db.QueryRow("SELECT id FROM users WHERE username = ? AND password = ?", req.Username, req.Password).Scan(&user.ID)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
}

//session建立
sessionID := "session_" + req.Username
sessionMap[sessionID] = &user
c.SetCookie("session_id", sessionID, 3600, "/", "localhost", false, true)

c.JSON(http.StatusOK, gin.H{"message": "登录成功"})
}
}
6 changes: 6 additions & 0 deletions 007WS-cry/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
database:
username: root
password: 20060820
host: localhost
port: 3306
name: myapp
Comment on lines +1 to +6
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Critical: Address security vulnerabilities in database configuration

There are two significant security concerns in this configuration:

  1. The database password is hardcoded in plain text. This is a severe security risk as it can lead to unauthorized access if the configuration file is compromised.
  2. The database username is set to "root", which is a highly privileged account. This violates the principle of least privilege and could potentially allow unintended changes to the database.

To address these security vulnerabilities:

  1. Use environment variables or a secure secret management system to store and retrieve sensitive information like passwords.
  2. Create a dedicated database user with only the necessary permissions for your application.

Example of using environment variables:

database:
  username: ${DB_USERNAME}
  password: ${DB_PASSWORD}
  host: localhost
  port: 3306
  name: myapp

Then, set these environment variables securely in your deployment environment.

Would you like me to provide a code snippet demonstrating how to read these environment variables in your application code?

🧰 Tools
🪛 yamllint

[error] 1-1: trailing spaces

(trailing-spaces)


[error] 6-6: no new line character at the end of file

(new-line-at-end-of-file)


🛠️ Refactor suggestion

Enhance configuration file structure and documentation

While the current structure is functional, consider the following improvements to enhance readability, maintainability, and scalability:

  1. Group related configurations under a common key.
  2. Add comments to explain the purpose of each configuration item.
  3. Structure the file to accommodate potential future configurations.

Here's an example of how you could restructure the configuration file:

# Database configuration
database:
  # Connection details for the application database
  connection:
    host: localhost
    port: 3306
    name: myapp
  # Credentials for database access (use environment variables in production)
  credentials:
    username: ${DB_USERNAME}
    password: ${DB_PASSWORD}

# Add other configuration sections as needed
# server:
#   port: 8080
#   host: 0.0.0.0

# logging:
#   level: info
#   file: /var/log/myapp.log

This structure allows for easy expansion and better organization of configuration items as your application grows.

🧰 Tools
🪛 yamllint

[error] 1-1: trailing spaces

(trailing-spaces)


[error] 6-6: no new line character at the end of file

(new-line-at-end-of-file)

37 changes: 37 additions & 0 deletions 007WS-cry/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module myapp

go 1.23.1
Comment on lines +1 to +3
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Update module name and Go version

  1. Consider using a more descriptive module name that reflects the project's purpose or structure.
  2. The specified Go version (1.23.1) is invalid. As of September 2024, the latest stable version is 1.21.x. Please update to a valid and current Go version.

Apply this diff to fix the Go version:

-go 1.23.1
+go 1.21
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
module myapp
go 1.23.1
module myapp
go 1.21


require github.com/gin-gonic/gin v1.10.0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Update Gin framework version

The specified version of the Gin framework (v1.10.0) is not valid. As of September 2024, the latest stable version is v1.9.x. Please update to the latest stable version to ensure compatibility and access to the latest features and bug fixes.

Apply this diff to update the Gin version:

-require github.com/gin-gonic/gin v1.10.0
+require github.com/gin-gonic/gin v1.9.1
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
require github.com/gin-gonic/gin v1.10.0
require github.com/gin-gonic/gin v1.9.1


require filippo.io/edwards25519 v1.1.0 // indirect

require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.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.20.0 // indirect
github.com/go-sql-driver/mysql v1.8.1
github.com/goccy/go-json v0.10.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // 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.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
Comment on lines +7 to +37
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Update indirect dependencies

Some of the indirect dependencies might be outdated. It's a good practice to keep dependencies up-to-date to benefit from bug fixes and security updates. Consider running go get -u to update all dependencies to their latest minor or patch versions.

Run the following command to update dependencies:

go get -u

After running this command, review the changes in the go.mod file and ensure that the updates don't introduce any breaking changes to your project.

83 changes: 83 additions & 0 deletions 007WS-cry/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/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.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
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.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
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.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
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.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/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.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
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/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
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.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
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.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
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.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
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=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
126 changes: 126 additions & 0 deletions 007WS-cry/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package main

import (
"database/sql"
"log"
"net/http"
"os"

"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"gopkg.in/yaml.v3"
)

type Config struct {
Database struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
Host string `yaml:"host"`
Port string `yaml:"port"`
Name string `yaml:"name"`
} `yaml:"database"`
}

func main() {
r := gin.Default()

//连接数据库
var config Config
configFile, err := os.ReadFile("config.yaml")
if err != nil {
log.Fatal("读取配置文件失败:", err)
}
err = yaml.Unmarshal(configFile, &config)
if err != nil {
log.Fatal("解析配置文件失败:", err)
}

dbConnectionString := config.Database.Username + ":" + config.Database.Password + "@tcp(" + config.Database.Host + ":" + config.Database.Port + ")/" + config.Database.Name

db, err := sql.Open("mysql", dbConnectionString)
if err != nil {
log.Fatal("连接数据库失败:", err)
}
Comment on lines +27 to +43
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling in database connection.

While the current error handling is functional, it could be more robust.

Consider adding a connection test after opening the database:

db, err := sql.Open("mysql", dbConnectionString)
if err != nil {
    log.Fatal("Failed to open database connection: ", err)
}

// Test the connection
err = db.Ping()
if err != nil {
    log.Fatal("Failed to ping database: ", err)
}

This ensures that not only was the connection opened, but it's also responsive.


defer db.Close()
/*db, err := sql.Open("mysql", "root:20060820@tcp(127.0.0.1:3306)/test")
if err != nil {
log.Fatal("连接数据库失败:", err)
}
defer db.Close()*/

//创建路由组
authGroup := r.Group("/auth")
{
//注册路由
authGroup.POST("/register", registerHandler(db))
//登录路由
authGroup.POST("/login", loginHandler(db))
}

questionGroup := r.Group("/question")
{
//提问路由
questionGroup.POST("/ask", askHandler(db))
//修改问题路由
questionGroup.POST("/update", updateHandler(db))
//回答问题路由
questionGroup.POST("/answer", answerHandler(db))
//搜索问题路由
questionGroup.POST("/search", searchHandler(db))
}

//返回注册界面
r.GET("/auth/register", func(c *gin.Context) {
c.HTML(http.StatusOK, "register.html", nil)
})

//返回登录界面
r.GET("/auth/login", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
})

//返回提问界面
r.GET("/question/ask", func(c *gin.Context) {
c.HTML(http.StatusOK, "ask.html", nil)
})

//返回修改问题界面
r.GET("/question/update", func(c *gin.Context) {
c.HTML(http.StatusOK, "update.html", nil)
})

//返回回答问题界面
r.GET("/question/answer", func(c *gin.Context) {
c.HTML(http.StatusOK, "answer.html", nil)
})

//返回搜索问题界面
r.GET("/question/search", func(c *gin.Context) {
c.HTML(http.StatusOK, "search.html", nil)
})

//静态资源目录
r.Static("/static", "./static")

//错误处理
r.Use(errorHandler)

r.Run(":8080")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider making the server port configurable.

The server is currently set to listen on a hardcoded port (8080).

Make the port configurable by adding it to your Config struct and using it here:

r.Run(":" + config.Server.Port)

Don't forget to add the corresponding field to your Config struct and config.yaml file.

}
Comment on lines +24 to +110
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Main function is functional but could be improved.

The main function successfully sets up the server and routes, but there are several areas for improvement:

  1. The function is quite long. Consider breaking it down into smaller, more focused functions for better readability and maintainability.

  2. Remove the commented-out database connection code (lines 46-50) as it's no longer needed and contains hardcoded credentials.

  3. Error handling could be more robust. For example, after connecting to the database, you should check db.Ping() to ensure the connection is valid.

  4. The server is set to listen on a hardcoded port (8080). Consider making this configurable.

Here's a suggestion for breaking down the main function:

func main() {
    config := loadConfig()
    db := connectToDatabase(config)
    defer db.Close()

    r := setupRouter(db)
    r.Run(":8080")
}

func loadConfig() Config {
    // Load and parse config file
}

func connectToDatabase(config Config) *sql.DB {
    // Connect to database and verify connection
}

func setupRouter(db *sql.DB) *gin.Engine {
    // Set up all routes and middleware
}

This structure improves readability and makes the code more modular.


// 错误处理函数
func errorHandler(c *gin.Context) {
c.Next()
if len(c.Errors) > 0 {
err := c.Errors[0]
switch err.Type {
case gin.ErrorTypePublic:
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
case gin.ErrorTypePrivate:
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "内部服务器错误"})
}
}
}
Loading