Sure, let's proceed to implement the Go application based on your plan. I'll walk through each step, making corrections and adjustments where necessary.
1. Project Setup
1.1 Environment Setup
Ensure you have the following installed:
- Go (latest stable version)
- Git
- SurrealDB
- A Go workspace set up
1.2 Project Initialization
Initialize the project:
mkdir confession-image-generator
cd confession-image-generator
go mod init github.com/yourusername/confession-image-generator
git init
1.3 Project Structure
Create the directory structure as outlined.
2. Define Data Models
Create internal/models/models.go:
package models
import (
"time"
)
type Confession struct {
ID string `json:"id" db:"id"`
Content string `json:"content" db:"content"`
DayNumber int `json:"dayNumber" db:"day_number"`
ImageURL string `json:"imageURL" db:"image_url"`
Status string `json:"status" db:"status"` // "pending", "approved", "rejected"
CreatedAt time.Time `json:"createdAt" db:"created_at"`
Replies []Reply `json:"replies,omitempty" db:"-"`
}
type Reply struct {
ID string `json:"id" db:"id"`
ConfessionID string `json:"confessionId" db:"confession_id"`
Content string `json:"content" db:"content"`
CreatedAt time.Time `json:"createdAt" db:"created_at"`
}
type User struct {
ID string `json:"id" db:"id"`
Username string `json:"username" db:"username"`
Password string `json:"-" db:"password"` // Password hash
IsAdmin bool `json:"isAdmin" db:"is_admin"`
}
Corrections:
- Changed struct tags to include
db for database field mapping.
- Added
omitempty to Replies to omit it from JSON if it's empty.
- Added explicit database field names in
db tags.
3. Database Setup
3.1 SurrealDB Installation
Follow the official SurrealDB documentation to install SurrealDB.
3.2 Database Connection
Create internal/database/surrealdb.go:
package database
import (
"context"
"fmt"
"time"
"github.com/surrealdb/surrealdb.go"
"github.com/yourusername/confession-image-generator/internal/models"
)
type SurrealDBClient struct {
DB *surrealdb.DB
}
func Connect(connectionString string) (*SurrealDBClient, error) {
db, err := surrealdb.New(connectionString)
if err != nil {
return nil, fmt.Errorf("failed to connect to SurrealDB: %w", err)
}
return &SurrealDBClient{DB: db}, nil
}
// Implement CRUD operations for Confession
func (c *SurrealDBClient) CreateConfession(ctx context.Context, confession *models.Confession) error {
confession.ID = surrealdb.NewUUID().String()
confession.CreatedAt = time.Now()
_, err := c.DB.Create("confession", confession)
return err
}
func (c *SurrealDBClient) GetConfession(ctx context.Context, id string) (*models.Confession, error) {
var confessions []models.Confession
err := c.DB.Select("confession", id, &confessions)
if err != nil {
return nil, err
}
if len(confessions) == 0 {
return nil, fmt.Errorf("confession not found")
}
return &confessions[0], nil
}
func (c *SurrealDBClient) UpdateConfession(ctx context.Context, confession *models.Confession) error {
confession.CreatedAt = time.Now()
_, err := c.DB.Update("confession", confession.ID, confession)
return err
}
func (c *SurrealDBClient) DeleteConfession(ctx context.Context, id string) error {
_, err := c.DB.Delete("confession", id)
return err
}
func (c *SurrealDBClient) ListConfessions(ctx context.Context, status string, limit, offset int) ([]models.Confession, error) {
var confessions []models.Confession
query := fmt.Sprintf("SELECT * FROM confession WHERE status = '%s' ORDER BY created_at DESC LIMIT %d START %d", status, limit, offset)
err := c.DB.Query(query, &confessions)
return confessions, err
}
// Implement similar functions for Reply
func (c *SurrealDBClient) CreateReply(ctx context.Context, reply *models.Reply) error {
reply.ID = surrealdb.NewUUID().String()
reply.CreatedAt = time.Now()
_, err := c.DB.Create("reply", reply)
return err
}
// Implement functions for User (Registration and Authentication)
func (c *SurrealDBClient) GetUserByUsername(ctx context.Context, username string) (*models.User, error) {
var users []models.User
query := fmt.Sprintf("SELECT * FROM user WHERE username = '%s'", username)
err := c.DB.Query(query, &users)
if err != nil {
return nil, err
}
if len(users) == 0 {
return nil, fmt.Errorf("user not found")
}
return &users[0], nil
}
Corrections & Notes:
- SurrealDB's Go client requires context for operations.
- Added
context.Context to function parameters.
- Implemented error handling and data retrieval according to SurrealDB's API.
- The plan didn't specify context usage; added as best practice.
- The code assumes that appropriate tables/collections (
confession, reply, user) exist.
4. Image Generation Module
Create internal/image/generator.go:
package image
import (
"bytes"
"image/color"
"io/ioutil"
"math"
"github.com/fogleman/gg"
"github.com/yourusername/confession-image-generator/internal/models"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
)
type ImageConfig struct {
Width int
Height int
FontSize float64
LineSpacing float64
Padding float64
GradientTop color.RGBA
GradientBottom color.RGBA
FontPath string
}
func GenerateImage(confession *models.Confession, config ImageConfig) ([]byte, error) {
dc := gg.NewContext(config.Width, config.Height)
// Draw background gradient
drawGradient(dc, config)
// Load font
if err := loadFont(dc, config.FontPath, config.FontSize); err != nil {
return nil, err
}
// Add day number
addDayNumber(dc, confession.DayNumber, config)
// Add confession text
addConfessionText(dc, confession.Content, config)
// If there are replies, add the first reply
if len(confession.Replies) > 0 {
addReplyText(dc, confession.Replies[0].Content, config)
}
// Encode to PNG
var buf bytes.Buffer
if err := dc.EncodePNG(&buf); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func drawGradient(dc *gg.Context, config ImageConfig) {
for y := 0; y < config.Height; y++ {
t := float64(y) / float64(config.Height)
r := uint8(float64(config.GradientTop.R)*(1-t) + float64(config.GradientBottom.R)*t)
g := uint8(float64(config.GradientTop.G)*(1-t) + float64(config.GradientBottom.G)*t)
b := uint8(float64(config.GradientTop.B)*(1-t) + float64(config.GradientBottom.B)*t)
dc.SetRGB255(int(r), int(g), int(b))
dc.DrawLine(0, float64(y), float64(config.Width), float64(y))
dc.Stroke()
}
}
func loadFont(dc *gg.Context, fontPath string, fontSize float64) error {
fontBytes, err := ioutil.ReadFile(fontPath)
if err != nil {
return err
}
f, err := opentype.Parse(fontBytes)
if err != nil {
return err
}
face, err := opentype.NewFace(f, &opentype.FaceOptions{
Size: fontSize,
DPI: 72,
Hinting: font.HintingFull,
})
if err != nil {
return err
}
dc.SetFontFace(face)
return nil
}
func addDayNumber(dc *gg.Context, dayNumber int, config ImageConfig) {
dayText := fmt.Sprintf("Day %d", dayNumber)
dc.SetRGB(1, 1, 1) // White color
dc.DrawStringAnchored(dayText, config.Width-config.Padding, config.Padding, 1, 0)
}
func addConfessionText(dc *gg.Context, text string, config ImageConfig) {
dc.SetRGB(1, 1, 1) // White color
maxWidth := float64(config.Width) - config.Padding*2
x := config.Padding
y := config.Height / 3
dc.DrawStringWrapped(text, x, y, 0, 0, maxWidth, config.LineSpacing, gg.AlignLeft)
}
func addReplyText(dc *gg.Context, text string, config ImageConfig) {
dc.SetRGB(1, 1, 0) // Yellow color for replies
maxWidth := float64(config.Width) - config.Padding*2
x := config.Padding
y := (config.Height / 3) * 2
dc.DrawStringWrapped(text, x, y, 0, 0, maxWidth, config.LineSpacing, gg.AlignLeft)
}
Corrections & Notes:
- Added code to load a font from a file.
drawGradient implementation uses interpolation between two colors.
- Used
bytes.Buffer to collect the PNG data.
- Used
ioutil.ReadFile and opentype package to load fonts.
- Added error handling for font loading and image encoding.
5. API Development
5.1 API Handlers
Create internal/api/handlers.go:
package api
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/yourusername/confession-image-generator/internal/database"
"github.com/yourusername/confession-image-generator/internal/image"
"github.com/yourusername/confession-image-generator/internal/models"
)
type Handler struct {
DB *database.SurrealDBClient
ImageConfig image.ImageConfig
}
func (h *Handler) SubmitConfession(c *gin.Context) {
var input struct {
Content string `json:"content" binding:"required"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
return
}
confession := &models.Confession{
Content: input.Content,
DayNumber: getCurrentDayNumber(),
Status: "pending",
}
ctx := context.Background()
if err := h.DB.CreateConfession(ctx, confession); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create confession"})
return
}
c.JSON(http.StatusOK, confession)
}
func (h *Handler) GetConfession(c *gin.Context) {
id := c.Param("id")
ctx := context.Background()
confession, err := h.DB.GetConfession(ctx, id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Confession not found"})
return
}
c.JSON(http.StatusOK, confession)
}
func (h *Handler) ListConfessions(c *gin.Context) {
status := c.Query("status")
if status == "" {
status = "approved"
}
limit := 20 // default limit
offset := 0 // default offset
ctx := context.Background()
confessions, err := h.DB.ListConfessions(ctx, status, limit, offset)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve confessions"})
return
}
c.JSON(http.StatusOK, confessions)
}
func (h *Handler) ModerateConfession(c *gin.Context) {
var input struct {
Status string `json:"status" binding:"required"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
return
}
id := c.Param("id")
ctx := context.Background()
confession, err := h.DB.GetConfession(ctx, id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Confession not found"})
return
}
confession.Status = input.Status
if confession.Status == "approved" {
// Generate image
imgData, err := image.GenerateImage(confession, h.ImageConfig)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate image"})
return
}
// Save image to file system or cloud storage
imagePath := fmt.Sprintf("public/images/confession_%s.png", confession.ID)
if err := ioutil.WriteFile(imagePath, imgData, 0644); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save image"})
return
}
confession.ImageURL = fmt.Sprintf("/images/confession_%s.png", confession.ID)
}
if err := h.DB.UpdateConfession(ctx, confession); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update confession"})
return
}
c.JSON(http.StatusOK, confession)
}
func (h *Handler) SubmitReply(c *gin.Context) {
var input struct {
Content string `json:"content" binding:"required"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
return
}
confessionID := c.Param("id")
reply := &models.Reply{
ConfessionID: confessionID,
Content: input.Content,
}
ctx := context.Background()
if err := h.DB.CreateReply(ctx, reply); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create reply"})
return
}
c.JSON(http.StatusOK, reply)
}
// Additional handlers for login/logout
Corrections & Notes:
- Corrected function signatures to include context.
- Added error handling and validation.
- Implemented image generation upon moderation approval.
- Simplified image storage by writing to a file; in production, you'd store it properly.
- The implementation assumes the existence of a public directory for serving images.
5.2 Middleware
Create internal/api/middleware.go:
package api
import (
"net/http"
"github.com/gin-gonic/gin"
)
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Check session or token
// If not authenticated:
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
}
func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Check if user is admin
// If not admin:
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Forbidden"})
return
}
}
Corrections & Notes:
- Implemented basic structure for authentication and admin middleware.
- In a real application, you'd integrate session management or JWT tokens.
6. Frontend Development
6.1 HTML Templates
Create the HTML templates in web/templates/. Here's an example for index.html:
<!-- web/templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Confession Submission</title>
<link rel="stylesheet" href="/static/css/styles.css">
</head>
<body>
<h1>Submit a Confession</h1>
<form id="confession-form">
<textarea name="content" id="content" cols="30" rows="10" placeholder="Your confession"></textarea>
<button type="submit">Submit</button>
</form>
<script src="/static/js/main.js"></script>
</body>
</html>
Notes:
- Ensure the form action and methods align with your API endpoints.
- Use proper templating syntax if required.
6.2 Static Assets
Create styles.css and main.js in web/static/.
7. Configuration
Create internal/config/config.go:
package config
import (
"image/color"
"os"
"strconv"
"github.com/yourusername/confession-image-generator/internal/image"
)
type Config struct {
DatabaseURL string
ServerAddress string
ImageConfig image.ImageConfig
}
func Load() *Config {
width, _ := strconv.Atoi(getEnv("IMAGE_WIDTH", "800"))
height, _ := strconv.Atoi(getEnv("IMAGE_HEIGHT", "600"))
fontSize, _ := strconv.ParseFloat(getEnv("FONT_SIZE", "24"), 64)
return &Config{
DatabaseURL: getEnv("DATABASE_URL", "http://localhost:8000"),
ServerAddress: getEnv("SERVER_ADDRESS", ":8080"),
ImageConfig: image.ImageConfig{
Width: width,
Height: height,
FontSize: fontSize,
// Add other image configurations here
GradientTop: color.RGBA{R: 255, G: 0, B: 0, A: 255},
GradientBottom: color.RGBA{R: 0, G: 0, B: 255, A: 255},
FontPath: getEnv("FONT_PATH", "./assets/fonts/Roboto-Regular.ttf"),
},
}
}
func getEnv(key, defaultValue string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return defaultValue
}
Corrections & Notes:
- Added environment variable handling.
- Ensured default values are provided.
8. Main Application
Create cmd/server/main.go:
package main
import (
"log"
"github.com/gin-gonic/gin"
"github.com/yourusername/confession-image-generator/internal/api"
"github.com/yourusername/confession-image-generator/internal/config"
"github.com/yourusername/confession-image-generator/internal/database"
)
func main() {
// Load configuration
cfg := config.Load()
// Initialize database
db, err := database.Connect(cfg.DatabaseURL)
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
// Set up Gin router
router := gin.Default()
// Load HTML templates
router.LoadHTMLGlob("web/templates/*")
// Serve static files
router.Static("/static", "./web/static")
router.Static("/images", "./public/images")
// Initialize handler
handler := &api.Handler{
DB: db,
ImageConfig: cfg.ImageConfig,
}
// Set up routes
router.GET("/", func(c *gin.Context) {
c.HTML(200, "index.html", nil)
})
router.POST("/confessions", handler.SubmitConfession)
router.GET("/confessions/:id", handler.GetConfession)
router.GET("/gallery", handler.ListConfessions)
router.POST("/confessions/:id/replies", handler.SubmitReply)
router.POST("/login", handler.Login)
router.POST("/logout", handler.Logout)
// Admin routes
admin := router.Group("/admin")
admin.Use(api.AdminMiddleware())
{
admin.GET("/", handler.AdminDashboard)
admin.POST("/confessions/:id/moderate", handler.ModerateConfession)
}
// Start server
log.Printf("Server running at %s", cfg.ServerAddress)
if err := router.Run(cfg.ServerAddress); err != nil {
log.Fatalf("Failed to run server: %v", err)
}
}
Corrections & Notes:
- Added logging statements.
- Fixed static file serving for images.
- Provided a simple handler for the home route.
9. Testing
9.1 Unit Tests
Create test files for each package, e.g., internal/database/surrealdb_test.go.
Example:
package database
import (
"context"
"testing"
"github.com/yourusername/confession-image-generator/internal/models"
)
func TestCreateConfession(t *testing.T) {
dbClient, err := Connect("http://localhost:8000")
if err != nil {
t.Fatalf("Failed to connect to database: %v", err)
}
confession := &models.Confession{
Content: "Test confession",
DayNumber: 1,
Status: "pending",
}
err = dbClient.CreateConfession(context.Background(), confession)
if err != nil {
t.Errorf("Failed to create confession: %v", err)
}
}
Notes:
- Use a test database or mock the database operations.
10. Deployment
10.1 Dockerfile
Create a Dockerfile:
# Use the official Go image as base
FROM golang:1.16-alpine
# Set the working directory
WORKDIR /app
# Copy go.mod and go.sum files
COPY go.mod go.sum ./
# Download dependencies
RUN go mod download
# Copy the source code
COPY . .
# Build the application
RUN go build -o server ./cmd/server
# Expose the port
EXPOSE 8080
# Command to run
CMD ["./server"]
10.2 Docker Compose
Create a docker-compose.yml file:
version: '3'
services:
app:
build: .
ports:
- '8080:8080'
volumes:
- .:/app
depends_on:
- surrealdb
surrealdb:
image: surrealdb/surrealdb:latest
ports:
- '8000:8000'
command: start --log debug --user root --pass root memory
11. Documentation
Update README.md with all relevant information.
12. Additional Considerations
Security
- Implement session management with secure cookies.
- Use HTTPS in production (handled by reverse proxy like Nginx).
- Sanitize user inputs to prevent XSS and SQL injection.
Error Handling
- Add more comprehensive error handling throughout the application.
- Use middleware to handle panics and return consistent error responses.
Configuration Management
- Use a
.env file or environment variables for configuration.
- Consider using a configuration management library.
Logging and Monitoring
- Implement structured logging.
- Integrate with monitoring tools if necessary.
By implementing the code above, we've created a basic Go web application according to your plan, making necessary corrections and adjustments. This forms a solid foundation upon which you can build and expand, adding more features and improving as needed.
If you need further assistance with specific parts of the application or have questions about certain implementations, feel free to ask!