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

亻尔女子 #4

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.idea
.idea
l1nk4i/config.toml
.gitignore
50 changes: 50 additions & 0 deletions l1nk4i/api/answer/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package answer

import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"l1nk4i/db"
"net/http"
)

func Create(c *gin.Context) {
questionID := c.Param("question-id")

var answerInfo struct {
Content string `json:"content"`
}

if err := c.ShouldBind(&answerInfo); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}

session := sessions.Default(c)
userID, exists := session.Get("user_id").(string)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}

// Verify that the question exists
_, err := db.GetQuestionByQuestionID(questionID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid question_id"})
return
}

answer := db.Answer{
AnswerID: uuid.New().String(),
UserID: userID,
QuestionID: questionID,
Content: answerInfo.Content,
}
if err := db.CreateAnswer(&answer); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "create answer error"})
return
}

c.JSON(http.StatusOK, gin.H{"answer_id": answer.AnswerID})
return
}
40 changes: 40 additions & 0 deletions l1nk4i/api/answer/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package answer

import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"l1nk4i/db"
"net/http"
)

func Delete(c *gin.Context) {
answerID := c.Param("answer-id")

// Verify user identity
session := sessions.Default(c)
userid, exists := session.Get("user_id").(string)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}

answer, err := db.GetAnswerByAnswerID(answerID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid answer_id"})
return
}

if answer.UserID != userid {
c.JSON(http.StatusForbidden, gin.H{"error": "permission denied"})
return
}

// Delete answer
err = db.DeleteAnswer(answerID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "delete answer error"})
return
}

c.JSON(http.StatusOK, gin.H{"msg": "delete answer successful!"})
}
20 changes: 20 additions & 0 deletions l1nk4i/api/answer/get.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package answer

import (
"github.com/gin-gonic/gin"
"l1nk4i/db"
"net/http"
)

// Get gets answers to the question by question_id
func Get(c *gin.Context) {
questionID := c.Param("question-id")

answers, err := db.GetAnswersByQuestionID(questionID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid question_id"})
return
}

c.JSON(http.StatusOK, gin.H{"data": answers})
}
49 changes: 49 additions & 0 deletions l1nk4i/api/answer/update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package answer

import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"l1nk4i/db"
"net/http"
)

func Update(c *gin.Context) {
answerID := c.Param("answer-id")

var answerInfo struct {
Content string `json:"content"`
}

if err := c.ShouldBindJSON(&answerInfo); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}

// Verify user identity
session := sessions.Default(c)
userid, exists := session.Get("user_id").(string)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}
Comment on lines +22 to +28
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance session handling and error messaging.

The current implementation correctly checks for user authentication, but there are a couple of improvements that can be made:

  1. The error message for invalid sessions could be more specific.
  2. It's a good practice to use constants for session keys to avoid typos and improve maintainability.

Consider applying the following changes:

  1. Improve the error message:
 if !exists {
-    c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
+    c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated", "details": "Valid session required"})
     return
 }
  1. Define a constant for the session key:
const UserIDKey = "user_id"

Then use it in the code:

-userid, exists := session.Get("user_id").(string)
+userid, exists := session.Get(UserIDKey).(string)


answer, err := db.GetAnswerByAnswerID(answerID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid answer_id"})
return
}

if answer.UserID != userid {
c.JSON(http.StatusForbidden, gin.H{"error": "permission denied"})
return
}

// Update answer
err = db.UpdateAnswer(answerID, answerInfo.Content)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid answer"})
return
}

c.JSON(http.StatusOK, gin.H{"msg": "update answer successful!"})
}
42 changes: 42 additions & 0 deletions l1nk4i/api/question/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package question

import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"l1nk4i/db"
"net/http"
)

func Create(c *gin.Context) {
var questionInfo struct {
Title string `json:"title"`
Content string `json:"content"`
}

if err := c.ShouldBind(&questionInfo); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}

session := sessions.Default(c)
userID, exists := session.Get("user_id").(string)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}
Comment on lines +22 to +27
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 adding validation for the user ID.

While the function correctly retrieves and checks for the existence of a user ID in the session, it doesn't validate the format or content of the user ID.

Consider adding a validation step for the user ID:

 	userID, exists := session.Get("user_id").(string)
 	if !exists {
 		c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
 		return
 	}
+	if !isValidUserID(userID) {
+		c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid user ID"})
+		return
+	}

 // Add this helper function
+func isValidUserID(id string) bool {
+	// Implement your validation logic here
+	// For example, check if it's a valid UUID
+	_, err := uuid.Parse(id)
+	return err == nil
+}

Committable suggestion was skipped due to low confidence.


question := db.Question{
QuestionID: uuid.New().String(),
UserID: userID,
Title: questionInfo.Title,
Content: questionInfo.Content,
}
if err := db.CreateQuestion(&question); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "create question error"})
return
}
Comment on lines +29 to +38
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation and improve error handling for question creation.

While the function correctly creates a new question and interacts with the database, there are a few areas for improvement:

  1. Input validation for the question title and content is missing.
  2. The error message for database interaction could be more specific.

Consider implementing these improvements:

  1. Add input validation:
+	if len(questionInfo.Title) == 0 || len(questionInfo.Content) == 0 {
+		c.JSON(http.StatusBadRequest, gin.H{"error": "Title and content cannot be empty"})
+		return
+	}
+	// Add more validation as needed (e.g., max length)
  1. Improve error handling:
 	if err := db.CreateQuestion(&question); err != nil {
-		c.JSON(http.StatusInternalServerError, gin.H{"error": "create question error"})
+		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create question: " + err.Error()})
 		return
 	}
📝 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
question := db.Question{
QuestionID: uuid.New().String(),
UserID: userID,
Title: questionInfo.Title,
Content: questionInfo.Content,
}
if err := db.CreateQuestion(&question); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "create question error"})
return
}
if len(questionInfo.Title) == 0 || len(questionInfo.Content) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Title and content cannot be empty"})
return
}
// Add more validation as needed (e.g., max length)
question := db.Question{
QuestionID: uuid.New().String(),
UserID: userID,
Title: questionInfo.Title,
Content: questionInfo.Content,
}
if err := db.CreateQuestion(&question); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create question: " + err.Error()})
return
}


c.JSON(http.StatusOK, gin.H{"question_id": question.QuestionID})
return
}
Comment on lines +40 to +42
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 using HTTP 201 Created status for successful question creation.

While the current implementation returns a 200 OK status, it's more RESTful to use 201 Created when a new resource is successfully created.

Consider modifying the response as follows:

-	c.JSON(http.StatusOK, gin.H{"question_id": question.QuestionID})
+	c.JSON(http.StatusCreated, gin.H{"question_id": question.QuestionID})
📝 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
c.JSON(http.StatusOK, gin.H{"question_id": question.QuestionID})
return
}
c.JSON(http.StatusCreated, gin.H{"question_id": question.QuestionID})
return
}

63 changes: 63 additions & 0 deletions l1nk4i/api/question/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package question

import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"l1nk4i/db"
"net/http"
)

func Delete(c *gin.Context) {
questionID := c.Param("question-id")

// Verify user identity
session := sessions.Default(c)
userid, exists := session.Get("user_id").(string)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}
Comment on lines +15 to +19
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the session user_id retrieval logic

The current code uses a type assertion to retrieve user_id from the session, but it incorrectly interprets the result. The type assertion .(string) returns two values: the asserted value and a boolean indicating success. The variable exists actually indicates whether the type assertion succeeded, not whether the user_id exists in the session.

To correctly check for the existence of user_id and ensure it's of type string, consider the following modification:

-userid, exists := session.Get("user_id").(string)
-if !exists {
+userIDInterface := session.Get("user_id")
+if userIDInterface == nil {
     c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
     return
 }
+userid, ok := userIDInterface.(string)
+if !ok {
+    c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
+    return
+}
📝 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
userid, exists := session.Get("user_id").(string)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}
userIDInterface := session.Get("user_id")
if userIDInterface == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}
userid, ok := userIDInterface.(string)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}


question, err := db.GetQuestionByQuestionID(questionID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid question_id"})
return
}

if question.UserID != userid {
c.JSON(http.StatusForbidden, gin.H{"error": "permission denied"})
return
}

// Delete question
err = db.DeleteQuestion(questionID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "delete question error"})
return
}

// Delete answers to the question
err = deleteAnswers(questionID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "delete answers error"})
return
}

c.JSON(http.StatusOK, gin.H{"msg": "delete question successful!"})
}

func deleteAnswers(questionID string) error {
answers, err := db.GetAnswersByQuestionID(questionID)
if err != nil {
return err
}

for _, answer := range *answers {
err = db.DeleteAnswer(answer.AnswerID)
if err != nil {
return err
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle errors during answer deletion more comprehensively

Currently, if an error occurs while deleting an individual answer, the function returns immediately, potentially leaving some answers undeleted. This could lead to inconsistent data states. Consider modifying the function to attempt deletion of all answers, collecting any errors, and handling them after all deletions have been attempted.

You can refactor the code as follows:

 func deleteAnswers(questionID string) error {
     answers, err := db.GetAnswersByQuestionID(questionID)
     if err != nil {
         return err
     }

-    for _, answer := range *answers {
-        err = db.DeleteAnswer(answer.AnswerID)
-        if err != nil {
-            return err
-        }
+    var deleteErrors []error
+    for _, answer := range *answers {
+        if err := db.DeleteAnswer(answer.AnswerID); err != nil {
+            deleteErrors = append(deleteErrors, err)
+        }
     }

-    return nil
+    if len(deleteErrors) > 0 {
+        // Aggregate errors or handle accordingly
+        return fmt.Errorf("errors occurred during answer deletion: %v", deleteErrors)
+    }
+    return nil
 }
📝 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
for _, answer := range *answers {
err = db.DeleteAnswer(answer.AnswerID)
if err != nil {
return err
}
}
var deleteErrors []error
for _, answer := range *answers {
if err := db.DeleteAnswer(answer.AnswerID); err != nil {
deleteErrors = append(deleteErrors, err)
}
}
if len(deleteErrors) > 0 {
// Aggregate errors or handle accordingly
return fmt.Errorf("errors occurred during answer deletion: %v", deleteErrors)
}
return nil


return nil
}
20 changes: 20 additions & 0 deletions l1nk4i/api/question/get.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package question

import (
"github.com/gin-gonic/gin"
"l1nk4i/db"
"net/http"
)

// Get gets question by question_id
func Get(c *gin.Context) {
questionID := c.Param("question-id")

question, err := db.GetQuestionByQuestionID(questionID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid question_id"})
return
}

c.JSON(http.StatusOK, gin.H{"data": question})
}
31 changes: 31 additions & 0 deletions l1nk4i/api/question/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package question

import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"l1nk4i/db"
"net/http"
)

// List lists user's all question_id
func List(c *gin.Context) {
session := sessions.Default(c)
userID, exists := session.Get("user_id").(string)
if !exists {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session"})
return
}

questions, err := db.GetQuestionByUserID(userID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session"})
return
}
Comment on lines +19 to +23
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling for database operations.

The database interaction is straightforward, but the error handling can be improved in two ways:

  1. The error message is incorrect for a database error.
  2. The error handling doesn't distinguish between different types of errors.

Consider implementing the following changes:

  1. Update the error message:
- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session"})
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
  1. Implement more granular error handling:
if err != nil {
    if err == db.ErrNotFound {
        c.JSON(http.StatusNotFound, gin.H{"error": "no questions found for user"})
    } else {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
    }
    return
}

This assumes that db.ErrNotFound is defined in your db package. If it's not, consider adding it to distinguish between "no results" and other database errors.


var questionIDs []string
for _, question := range *questions {
questionIDs = append(questionIDs, question.QuestionID)
}

c.JSON(http.StatusOK, gin.H{"question_id": questionIDs})
}
Comment on lines +25 to +31
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 handling the case of no questions found.

The extraction of question IDs and the response format look good. However, there's no specific handling for the case where no questions are found for the user.

Consider adding a check for empty results:

if len(questionIDs) == 0 {
    c.JSON(http.StatusOK, gin.H{"message": "No questions found for user", "question_id": []string{}})
} else {
    c.JSON(http.StatusOK, gin.H{"question_id": questionIDs})
}

This will provide a more informative response when a user has no questions, while still maintaining the expected response structure.

18 changes: 18 additions & 0 deletions l1nk4i/api/question/search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package question

import (
"github.com/gin-gonic/gin"
"l1nk4i/db"
"net/http"
)

func Search(c *gin.Context) {
searchContent := c.Query("content")

questions, err := db.SearchQuestions(searchContent)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid content"})
}

c.JSON(http.StatusOK, gin.H{"data": questions})
}
50 changes: 50 additions & 0 deletions l1nk4i/api/question/update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package question

import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"l1nk4i/db"
"net/http"
)

func Update(c *gin.Context) {
questionID := c.Param("question-id")

var questionInfo struct {
Title string `json:"title"`
Content string `json:"content"`
}

if err := c.ShouldBind(&questionInfo); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}

// Verify user identity
session := sessions.Default(c)
userid, exists := session.Get("user_id").(string)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session"})
return
}

question, err := db.GetQuestionByQuestionID(questionID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid question_id"})
return
}

if question.UserID != userid {
c.JSON(http.StatusForbidden, gin.H{"error": "permission denied"})
return
}

// Update question
err = db.UpdateQuestion(questionID, questionInfo.Title, questionInfo.Content)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "update question error"})
return
}

c.JSON(http.StatusOK, gin.H{"msg": "update question successful!"})
}
Loading