// main.go package main import ( "database/sql" "encoding/json" "log" "net/http" _ "github.com/mattn/go-sqlite3" ) type EmojiClick struct { PostID string `json:"post_id"` Emoji string `json:"emoji"` } func main() { // Connect to the SQLite database db, err := sql.Open("sqlite3", "./emoji_counter.db") if err != nil { log.Fatal(err) } defer db.Close() // Execute schema SQL to create tables schema := `CREATE TABLE IF NOT EXISTS emoji_clicks ( id INTEGER PRIMARY KEY AUTOINCREMENT, post_id TEXT NOT NULL, emoji TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP );` _, err = db.Exec(schema) if err != nil { log.Fatal(err) } // Define the HTTP handler for emoji clicks http.HandleFunc("/emoji-click", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) return } var emojiClick EmojiClick if err := json.NewDecoder(r.Body).Decode(&emojiClick); err != nil { http.Error(w, "Bad request", http.StatusBadRequest) return } _, err := db.Exec("INSERT INTO emoji_clicks (post_id, emoji) VALUES (?, ?)", emojiClick.PostID, emojiClick.Emoji) if err != nil { http.Error(w, "Failed to save emoji click", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }) // Define the HTTP handler for getting emoji counts http.HandleFunc("/emoji-counts", func(w http.ResponseWriter, r *http.Request) { postID := r.URL.Query().Get("post_id") if postID == "" { http.Error(w, "post_id is required", http.StatusBadRequest) return } rows, err := db.Query("SELECT emoji, COUNT(*) as count FROM emoji_clicks WHERE post_id = ? GROUP BY emoji", postID) if err != nil { http.Error(w, "Failed to get emoji counts", http.StatusInternalServerError) return } defer rows.Close() emojiCounts := make(map[string]int) for rows.Next() { var emoji string var count int if err := rows.Scan(&emoji, &count); err != nil { http.Error(w, "Failed to parse emoji counts", http.StatusInternalServerError) return } emojiCounts[emoji] = count } if err := json.NewEncoder(w).Encode(emojiCounts); err != nil { http.Error(w, "Failed to encode response", http.StatusInternalServerError) return } }) // Start the HTTP server log.Println("Starting server on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) }