Created
January 7, 2025 13:44
-
-
Save febuiles/9c04b20e3ddbda0dbd37dca1cbdd1c48 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"log" | |
"net/http" | |
_ "github.com/mattn/go-sqlite3" | |
) | |
func main() { | |
http.HandleFunc("/get_tags", func(w http.ResponseWriter, r *http.Request) { | |
if r.Method != http.MethodGet { | |
w.Header().Set("Allow", http.MethodGet) | |
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) | |
return | |
} | |
w.Header().Set("Content-Type", "application/json") | |
query := r.URL.Query() | |
url := query.Get("url") | |
// json.NewEncoder(w).Encode(user) | |
w.Write([]byte(url)) | |
}) | |
log.Println("Server is running.") | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} | |
var db *sql.DB | |
func initDB() { | |
var activitiesSchema = `CREATE TABLE IF NOT EXISTS activities ( | |
id INTEGER PRIMARY KEY AUTOINCREMENT, | |
actor_id INTEGER NOT NULL, | |
action INTEGER NOT NULL, | |
object TEXT NOT NULL, | |
updated_at TEXT NOT NULL)` | |
var err error | |
db, err = sql.Open("sqlite3", "./data.db") | |
if err != nil { | |
log.Fatal(err) | |
} | |
_, err = db.Exec(activitiesSchema) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
type Activity struct { | |
ID int | |
ActorID int | |
Action int | |
Object string | |
UpdatedAt string | |
} | |
func getActivity(db *sql.DB, id int) (*Activity, error) { | |
query := `SELECT id, actor_id, action, object, updated_at FROM activities WHERE id = ?` | |
row := db.QueryRow(query, id) | |
activity := &Activity{} | |
err := row.Scan(&activity.ID, &activity.ActorID, &activity.Action, &activity.Object, &activity.UpdatedAt) | |
if err != nil { | |
if err == sql.ErrNoRows { | |
return nil, fmt.Errorf("activity with ID %d not found", id) | |
} | |
return nil, err | |
} | |
return activity, nil | |
} | |
func createActivity(db *sql.DB, actorID int, action int, object string, updatedAt string) (int64, error) { | |
query := `INSERT INTO activities (actor_id, action, object, updated_at) VALUES (?, ?, ?, ?)` | |
result, err := db.Exec(query, actorID, action, object, updatedAt) | |
if err != nil { | |
return 0, fmt.Errorf("failed to insert activity: %w", err) | |
} | |
activityID, err := result.LastInsertId() | |
if err != nil { | |
return 0, fmt.Errorf("failed to retrieve last insert ID: %w", err) | |
} | |
return activityID, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment