Save and List Photos
Add two endpoints to the App from Your First Route. POST /api/v1/photos saves a photo's storage key in SQLite. GET /api/v1/photos lists saved records, newest first, even after you restart the App.
Prerequisites
Enable SQLite, apply the photos migration, then generate PhotoRepo and add ListNewest. Work in the same Project and keep forj dev stopped while you add the service and controller.
Save Photo Metadata
Create internal/photos/service.go. The service takes a repository and returns a response with the saved ID and storage key.
package photos
import (
"context"
"time"
)
// Summary exposes the photo fields used by callers.
type Summary struct {
ID int64 `json:"id"`
StorageKey string `json:"storage_key"`
}
// Service saves and lists photo records.
type Service struct {
repo *PhotoRepo
}
// NewService accepts the repository registered by make:model.
func NewService(repo *PhotoRepo) *Service {
return &Service{repo: repo}
}
// Save records a storage key and returns its assigned ID.
func (s *Service) Save(ctx context.Context, key string) (Summary, error) {
photo := Photo{StorageKey: key, CreatedAt: time.Now().UTC()}
if err := s.repo.WithContext(ctx).Create(&photo); err != nil {
return Summary{}, err
}
return Summary{ID: photo.Id.ValueOrZero(), StorageKey: photo.StorageKey}, nil
}
// ListNewest returns saved photos newest first.
func (s *Service) ListNewest(ctx context.Context) ([]Summary, error) {
photos, err := s.repo.ListNewest(ctx)
if err != nil {
return nil, err
}
result := make([]Summary, 0, len(photos))
for _, photo := range photos {
result = append(result, Summary{
ID: photo.Id.ValueOrZero(), StorageKey: photo.StorageKey,
})
}
return result, nil
}In app/wire/inject_services_app.go, import your/module/internal/photos using your Project's module path. Add photos.NewService to the existing appSet. The repository constructor is already present in app/wire/inject_repositories_app.go from make:model.
Expose the Routes
Generate the photos controller and its registration.
forj make:controller photos --no-openReplace internal/photos/controller.go with these handlers. The POST route applies the body limit from Requests and Validation, then checks the storage key before calling the service.
package photos
import (
"errors"
"net/http"
"strings"
"github.com/goforj/web"
"github.com/goforj/web/webmiddleware"
)
// Controller exposes photo storage metadata over HTTP.
type Controller struct {
service *Service
}
// NewController receives the service constructed by Wire.
func NewController(service *Service) *Controller {
return &Controller{service: service}
}
// Routes registers the photos list and creation handlers.
func (c *Controller) Routes() []web.Route {
return []web.Route{
web.NewRoute(http.MethodGet, "/photos", c.Index),
web.NewRoute(http.MethodPost, "/photos", c.Store, webmiddleware.BodyLimit("16KB")).
WithMiddlewareNames("webmiddleware.BodyLimit"),
}
}
// Index lists the saved photo records.
func (c *Controller) Index(ctx web.Context) error {
photos, err := c.service.ListNewest(ctx.Context())
if err != nil {
return err
}
return ctx.JSON(http.StatusOK, photos)
}
// Store validates the storage key and saves the photo record.
func (c *Controller) Store(ctx web.Context) error {
var input struct {
StorageKey string `json:"storage_key"`
}
if err := ctx.Bind(&input); err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
status := http.StatusRequestEntityTooLarge
return ctx.Text(status, http.StatusText(status))
}
return ctx.JSON(http.StatusBadRequest, map[string]string{"error": "invalid_payload"})
}
key := strings.TrimSpace(input.StorageKey)
if key == "" {
return ctx.JSON(http.StatusUnprocessableEntity, map[string]string{"error": "storage_key_required"})
}
photo, err := c.service.Save(ctx.Context(), key)
if err != nil {
return err
}
return ctx.JSON(http.StatusCreated, photo)
}Verify Persistence
Start the App with forj dev. After Dev ready, save a photo in a second terminal. Use your configured port if it differs from 3000.
curl -i http://localhost:3000/api/v1/photos \
-H 'Content-Type: application/json' \
--data '{"storage_key":"sunrise.jpg"}'Expect 201 Created. An empty table starts at ID 1. Keep the ID the response actually returns for the next lesson.
{"id":1,"storage_key":"sunrise.jpg"}Stop forj dev with Ctrl+C and start it again. After Dev ready, list the saved photos.
curl http://localhost:3000/api/v1/photosExpect 200 OK and a list containing the same photo ID and storage key.
[{"id":1,"storage_key":"sunrise.jpg"}]Next Steps
Use the saved photo ID to run a photo job in a worker. See File Storage to store image bytes when you add uploads.