gofasta g task
Generates an async task handler file for processing work asynchronously using hibiken/asynq . Tasks are useful for offloading work from the HTTP request/response cycle, such as sending emails, processing uploads, or triggering external API calls.
Usage
gofasta g task <Name>This command has no flags.
Examples
Generate a task for cleaning expired sessions:
gofasta g task CleanExpiredSessionsGenerate a task for sending notifications:
gofasta g task SendNotificationWhat It Generates
Running gofasta g task CleanExpiredSessions creates one file:
app/tasks/clean_expired_sessions.goGenerated Code
// app/tasks/clean_expired_sessions.go
package tasks
import (
"context"
"encoding/json"
"github.com/hibiken/asynq"
)
const TypeCleanExpiredSessions = "clean_expired_sessions"
// CleanExpiredSessionsPayload contains the data needed to execute this task.
type CleanExpiredSessionsPayload struct {
// TODO: Add payload fields here
}
// HandleCleanExpiredSessions processes the CleanExpiredSessions task.
func HandleCleanExpiredSessions(ctx context.Context, t *asynq.Task) error {
var payload CleanExpiredSessionsPayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
return err
}
// TODO: Implement task logic here
return nil
}
// EnqueueCleanExpiredSessions creates and enqueues a CleanExpiredSessions task.
func EnqueueCleanExpiredSessions(client *asynq.Client, payload CleanExpiredSessionsPayload) (*asynq.TaskInfo, error) {
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
task := asynq.NewTask(TypeCleanExpiredSessions, data)
return client.Enqueue(task)
}Task vs Job
| Feature | Task | Job |
|---|---|---|
| Library | hibiken/asynq | scheduler.Job interface |
| Trigger | Enqueued from code (manual) | Cron schedule (automatic) |
| Payload | Carries a custom payload | None (runs with context only) |
| Use case | Event-driven async processing | Periodic maintenance |
| Pattern | Handle function + Enqueue helper | Name() + Run() methods |
Enqueuing Tasks
To enqueue a task from a service or controller:
func (s *UserServiceImpl) Register(req dtos.RegisterRequest) (*dtos.UserResponse, error) {
user, err := s.repo.Create(mapToUser(req))
if err != nil {
return nil, err
}
// Enqueue the async task
_, err = tasks.EnqueueCleanExpiredSessions(s.asynqClient, tasks.CleanExpiredSessionsPayload{
// populate fields
})
if err != nil {
slog.Error("failed to enqueue task", "error", err)
}
return dtos.ToUserResponse(user), nil
}Related
- gofasta g job — generate a scheduled background job instead
- gofasta g scaffold — generate a full resource
- gofasta dev — start the dev server which also runs the task worker
Last updated on