goblog/server.go
2024-12-07 17:45:46 -05:00

86 lines
1.9 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"log"
"database/sql"
"os"
"net"
"goblog-backend/db"
)
func main() {
db, err := db.ConnectDB()
if err != nil {
log.Fatal(err)
}
defer db.Close()
socketPath := "/tmp/goblog.sock"
if err := os.RemoveAll(socketPath); err != nil {
log.Fatalf("Failed to delete socket: %v", err)
}
listener, err := net.Listen("unix", socketPath)
if err != nil {
log.Fatalf("Failed to create socket: %v", err)
}
defer listener.Close()
http.HandleFunc("/posts", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
posts, err := GetPosts(db)
if err != nil {
http.Error(w, "Failed to fetch posts", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(posts)
} else if r.Method == http.MethodPost {
var post Post
err := json.NewDecoder(r.Body).Decode(&post)
if err != nil {
http.Error(w, "Failed to create post", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
})
// replace with the open port!
fmt.Println("[INFO] Welcome to goblog!")
log.Println ("[INFO] Server starting on socket:", socketPath)
log.Fatal(http.Serve(listener, nil))
}
func GetPosts(db *sql.DB) ([]Post, error) {
rows, err := db.Query("SELECT id, title, content, created_at FROM posts")
if err != nil {
return nil, err
}
defer rows.Close()
var posts []Post
for rows.Next() {
var post Post
if err := rows.Scan(&post.ID, &post.Title, &post.Content, &post.CreatedAt); err != nil {
return nil, err
}
posts = append(posts, post)
}
return posts, nil
}
func CreatePost(db *sql.DB, post Post) error {
_, err := db.Exec("INSERT INTO posts (title, content, created_at) VALUES ($1, $2, NOW())", post.Title, post.Content)
return err
}
type Post struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"title"`
CreatedAt string `json:"created_at"`
}