commit ca5116459896247a670babdffe88934acdfb2eb3 Author: suvodip ghosh Date: Tue Jun 24 13:42:46 2025 +0000 first commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..45ae33c --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module sp_comments_api + +go 1.13 + +require github.com/go-sql-driver/mysql v1.5.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5613e94 --- /dev/null +++ b/go.sum @@ -0,0 +1,42 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/go-sql-driver/mysql v1.4.0 h1:7LxgVwFb2hIQtMm87NdgAVfXjnt4OePseqT1tKx+opk= +github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= +github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= +google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= diff --git a/main.go b/main.go new file mode 100644 index 0000000..be1ad9b --- /dev/null +++ b/main.go @@ -0,0 +1,555 @@ +package main + +import ( + "database/sql" + "encoding/json" + "fmt" + "log" + "math/rand" + "net/http" + "strings" + "sync" + "time" + + _ "github.com/go-sql-driver/mysql" +) + +type Comment struct { + ID int `json:"id,omitempty"` + CommentID string `json:"comment_id"` + TopicID string `json:"topic_id"` + SiliconID string `json:"silicon_id"` + PbID string `json:"pb_id"` + UserID string `json:"user_id"` + UserName string `json:"user_name"` + CommentText string `json:"comment_text"` + IsApproved bool `json:"is_approved"` + ParentCommentID sql.NullString `json:"parent_comment_id,omitempty"` + CreatedAt time.Time `json:"created_at,omitempty"` + UpdatedAt time.Time `json:"updated_at,omitempty"` + Replies []Comment `json:"replies,omitempty"` +} + +var ( + db *sql.DB + idCounter uint64 + mutex sync.Mutex +) + +const ( + idPrefix = "CMT" + idLength = 10 + baseChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" +) + +func main() { + // Database configuration + dbUser := "sp" + dbPass := "0000" + dbHost := "65.108.85.191" + dbPort := "3306" + dbName := "sp_hostapi" + + dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", dbUser, dbPass, dbHost, dbPort, dbName) + + var err error + db, err = sql.Open("mysql", dsn) + if err != nil { + log.Fatal(err) + } + defer db.Close() + + db.SetMaxOpenConns(25) + db.SetMaxIdleConns(25) + db.SetConnMaxLifetime(5 * time.Minute) + + if err = db.Ping(); err != nil { + log.Fatal(err) + } + + if err = initIDCounter(); err != nil { + log.Fatal(err) + } + + // Set up HTTP server with CORS middleware + mux := http.NewServeMux() + mux.HandleFunc("/comments", corsMiddleware(handleComments)) + mux.HandleFunc("/comments/reply", corsMiddleware(handleReply)) + mux.HandleFunc("/comments/thread/", corsMiddleware(handleCommentThread)) + mux.HandleFunc("/comments/approve", corsMiddleware(handleCommentApproval)) + mux.HandleFunc("/health", corsMiddleware(healthCheck)) + mux.HandleFunc("/comments/", corsMiddleware(handleSingleComment)) + + log.Println("Server started on :8080") + log.Fatal(http.ListenAndServe(":8080", mux)) +} + +func corsMiddleware(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") + + if r.Method == "OPTIONS" { + w.WriteHeader(http.StatusNoContent) + return + } + + next(w, r) + } +} + +func healthCheck(w http.ResponseWriter, r *http.Request) { + if err := db.Ping(); err != nil { + http.Error(w, "DB connection error", http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusOK) + w.Write([]byte("OK")) +} + +func handleComments(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case "POST": + insertComment(w, r, "") + case "GET": + getComments(w, r) + default: + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + } +} + +func handleReply(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + var req struct { + ParentCommentID string `json:"parent_comment_id"` + TopicID string `json:"topic_id"` + SiliconID string `json:"silicon_id"` + PbID string `json:"pb_id"` + UserID string `json:"user_id"` + UserName string `json:"user_name"` + CommentText string `json:"comment_text"` + IsApproved bool `json:"is_approved"` + } + + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "Invalid request payload", http.StatusBadRequest) + return + } + + // Create comment with proper NullString handling + comment := Comment{ + TopicID: req.TopicID, + SiliconID: req.SiliconID, + PbID: req.PbID, + UserID: req.UserID, + UserName: req.UserName, + CommentText: req.CommentText, + IsApproved: req.IsApproved, + ParentCommentID: sql.NullString{ + String: req.ParentCommentID, + Valid: req.ParentCommentID != "", + }, + } + + // Convert to JSON and pass to insertComment + jsonData, err := json.Marshal(comment) + if err != nil { + http.Error(w, "Error creating request", http.StatusInternalServerError) + return + } + + // Create a new request with the properly formatted JSON + newReq, err := http.NewRequest("POST", "", strings.NewReader(string(jsonData))) + if err != nil { + http.Error(w, "Error creating request", http.StatusInternalServerError) + return + } + + // Call insertComment with the parent ID + insertComment(w, newReq, req.ParentCommentID) +} + +func insertComment(w http.ResponseWriter, r *http.Request, parentCommentID string) { + var comment Comment + if err := json.NewDecoder(r.Body).Decode(&comment); err != nil { + http.Error(w, "Invalid request payload: "+err.Error(), http.StatusBadRequest) + return + } + + // Validate required fields + if comment.TopicID == "" || comment.SiliconID == "" || comment.PbID == "" || + comment.UserID == "" || comment.UserName == "" || comment.CommentText == "" { + http.Error(w, "All fields except is_approved are required", http.StatusBadRequest) + return + } + + // Generate unique ID + comment.CommentID = generateUniqueID() + comment.CreatedAt = time.Now() + comment.UpdatedAt = time.Now() + + // Handle parent comment reference + if parentCommentID != "" { + comment.ParentCommentID = sql.NullString{ + String: parentCommentID, + Valid: true, + } + // Verify parent exists + var exists bool + err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM commentsdb WHERE comment_id = ?)", parentCommentID).Scan(&exists) + if err != nil || !exists { + http.Error(w, "Parent comment not found", http.StatusBadRequest) + return + } + } else { + comment.ParentCommentID = sql.NullString{Valid: false} + } + + // Insert the comment + _, err := db.Exec( + `INSERT INTO commentsdb + (comment_id, topic_id, silicon_id, pb_id, user_id, user_name, + comment_text, is_approved, parent_comment_id, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + comment.CommentID, + comment.TopicID, + comment.SiliconID, + comment.PbID, + comment.UserID, + comment.UserName, + comment.CommentText, + comment.IsApproved, + comment.ParentCommentID, + comment.CreatedAt, + comment.UpdatedAt, + ) + if err != nil { + http.Error(w, "Failed to insert comment: "+err.Error(), http.StatusInternalServerError) + return + } + + // Return the complete comment + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(comment) +} + +func getComments(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + topicID := query.Get("topic_id") + // siliconID := query.Get("silicon_id") + // pbID := query.Get("pb_id") + + if topicID == "" { + http.Error(w, "topic_id is required", http.StatusBadRequest) + return + } + + baseQuery := `SELECT id, comment_id, topic_id, silicon_id, pb_id, user_id, user_name, + comment_text, is_approved, parent_comment_id, created_at, updated_at + FROM commentsdb WHERE topic_id = ? AND is_approved = 1` + + args := []interface{}{topicID} + + // Add optional filters if provided and not "null" + // if siliconID != "" && siliconID != "null" { + // baseQuery += " AND silicon_id = ?" + // args = append(args, siliconID) + // } + // if pbID != "" && pbID != "null" { + // baseQuery += " AND pb_id = ?" + // args = append(args, pbID) + // } + + baseQuery += " ORDER BY created_at DESC" + + log.Printf("Executing query: %s\nParameters: %v\n", baseQuery, args) + + rows, err := db.Query(baseQuery, args...) + if err != nil { + http.Error(w, "Database query failed: "+err.Error(), http.StatusInternalServerError) + return + } + defer rows.Close() + + var comments []Comment + for rows.Next() { + var comment Comment + var parentID sql.NullString + err := rows.Scan( + &comment.ID, + &comment.CommentID, + &comment.TopicID, + &comment.SiliconID, + &comment.PbID, + &comment.UserID, + &comment.UserName, + &comment.CommentText, + &comment.IsApproved, + &parentID, + &comment.CreatedAt, + &comment.UpdatedAt, + ) + if err != nil { + http.Error(w, "Failed to scan comment: "+err.Error(), http.StatusInternalServerError) + return + } + comment.ParentCommentID = parentID + comments = append(comments, comment) + } + + if comments == nil { + comments = []Comment{} + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(comments) +} + +func handleCommentThread(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + pathParts := strings.Split(r.URL.Path, "/") + if len(pathParts) < 4 { + http.Error(w, "Invalid comment ID", http.StatusBadRequest) + return + } + commentID := pathParts[3] + + var parentComment Comment + var parentID sql.NullString + err := db.QueryRow( + `SELECT id, comment_id, topic_id, silicon_id, pb_id, user_id, user_name, + comment_text, is_approved, parent_comment_id, created_at, updated_at + FROM commentsdb WHERE comment_id = ?`, + commentID, + ).Scan( + &parentComment.ID, + &parentComment.CommentID, + &parentComment.TopicID, + &parentComment.SiliconID, + &parentComment.PbID, + &parentComment.UserID, + &parentComment.UserName, + &parentComment.CommentText, + &parentComment.IsApproved, + &parentID, + &parentComment.CreatedAt, + &parentComment.UpdatedAt, + ) + + if err != nil { + if err == sql.ErrNoRows { + http.Error(w, "Parent comment not found", http.StatusNotFound) + } else { + http.Error(w, "Database error", http.StatusInternalServerError) + } + return + } + + parentComment.ParentCommentID = parentID + + replies, err := getRepliesRecursive(commentID) + if err != nil { + http.Error(w, "Error fetching replies", http.StatusInternalServerError) + return + } + + parentComment.Replies = replies + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(parentComment) +} + +func getRepliesRecursive(parentID string) ([]Comment, error) { + rows, err := db.Query( + `SELECT id, comment_id, topic_id, silicon_id, pb_id, user_id, user_name, + comment_text, is_approved, parent_comment_id, created_at, updated_at + FROM commentsdb WHERE parent_comment_id = ? ORDER BY created_at ASC`, + parentID, + ) + if err != nil { + return nil, fmt.Errorf("query failed: %v", err) + } + defer rows.Close() + + var replies []Comment + for rows.Next() { + var reply Comment + var parentID sql.NullString + err := rows.Scan( + &reply.ID, + &reply.CommentID, + &reply.TopicID, + &reply.SiliconID, + &reply.PbID, + &reply.UserID, + &reply.UserName, + &reply.CommentText, + &reply.IsApproved, + &parentID, + &reply.CreatedAt, + &reply.UpdatedAt, + ) + if err != nil { + return nil, fmt.Errorf("scan failed: %v", err) + } + reply.ParentCommentID = parentID + + nestedReplies, err := getRepliesRecursive(reply.CommentID) + if err != nil { + return nil, fmt.Errorf("recursive query failed: %v", err) + } + reply.Replies = nestedReplies + + replies = append(replies, reply) + } + + return replies, nil +} + +func handleCommentApproval(w http.ResponseWriter, r *http.Request) { + if r.Method != "PUT" { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + var req struct { + CommentID string `json:"comment_id"` + IsApproved bool `json:"is_approved"` + } + + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "Invalid request payload", http.StatusBadRequest) + return + } + + _, err := db.Exec( + "UPDATE commentsdb SET is_approved = ? WHERE comment_id = ?", + req.IsApproved, + req.CommentID, + ) + if err != nil { + http.Error(w, "Failed to update comment", http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"status": "success"}) +} + +func handleSingleComment(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + pathParts := strings.Split(r.URL.Path, "/") + if len(pathParts) < 3 { + http.Error(w, "Invalid comment ID", http.StatusBadRequest) + return + } + commentID := pathParts[2] + + var comment Comment + var parentID sql.NullString + + err := db.QueryRow( + `SELECT id, comment_id, topic_id, silicon_id, pb_id, user_id, user_name, + comment_text, is_approved, parent_comment_id, created_at, updated_at + FROM commentsdb WHERE comment_id = ?`, + commentID, + ).Scan( + &comment.ID, + &comment.CommentID, + &comment.TopicID, + &comment.SiliconID, + &comment.PbID, + &comment.UserID, + &comment.UserName, + &comment.CommentText, + &comment.IsApproved, + &parentID, + &comment.CreatedAt, + &comment.UpdatedAt, + ) + + if err != nil { + if err == sql.ErrNoRows { + http.Error(w, "Comment not found", http.StatusNotFound) + } else { + http.Error(w, "Database error", http.StatusInternalServerError) + } + return + } + + comment.ParentCommentID = parentID + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(comment) +} + +func generateUniqueID() string { + mutex.Lock() + defer mutex.Unlock() + + idCounter++ + + var id strings.Builder + id.WriteString(idPrefix) + + n := idCounter + for i := 0; i < idLength-len(idPrefix)-2; i++ { + id.WriteByte(baseChars[n%36]) + n /= 36 + } + + rand.Seed(time.Now().UnixNano()) + for i := 0; i < 2; i++ { + id.WriteByte(baseChars[rand.Intn(36)]) + } + + return id.String() +} + +func initIDCounter() error { + var maxID sql.NullString + err := db.QueryRow("SELECT MAX(comment_id) FROM commentsdb").Scan(&maxID) + if err != nil { + return fmt.Errorf("error getting max ID: %v", err) + } + + if !maxID.Valid { + idCounter = 0 + return nil + } + + if !strings.HasPrefix(maxID.String, idPrefix) { + return fmt.Errorf("invalid ID format in database") + } + + trimmed := strings.TrimPrefix(maxID.String, idPrefix) + if len(trimmed) < 2 { + return fmt.Errorf("ID too short") + } + + counterPart := trimmed[:len(trimmed)-2] + + var counter uint64 + for _, c := range counterPart { + idx := strings.IndexByte(baseChars, byte(c)) + if idx == -1 { + return fmt.Errorf("invalid character in ID") + } + counter = counter*36 + uint64(idx) + } + + idCounter = counter + return nil +} \ No newline at end of file diff --git a/test.json b/test.json new file mode 100644 index 0000000..7f7b9e5 --- /dev/null +++ b/test.json @@ -0,0 +1 @@ +{"parent_comment_id":"CMT30003JJ","comment_text":"Test"}