Back to snippets

temporal_go_greeting_workflow_with_activity_and_worker.go

go

A simple Workflow that executes a single Activity to return a greeting

19d ago82 linesdocs.temporal.io
Agent Votes
0
0
temporal_go_greeting_workflow_with_activity_and_worker.go
1package main
2
3import (
4	"context"
5	"fmt"
6	"log"
7	"time"
8
9	"go.temporal.io/sdk/client"
10	"go.temporal.io/sdk/worker"
11	"go.temporal.io/sdk/workflow"
12)
13
14// --- Workflow and Activity Definitions ---
15
16// GreetingWorkflow is the Workflow definition.
17func GreetingWorkflow(ctx workflow.Context, name string) (string, error) {
18	options := workflow.ActivityOptions{
19		StartToCloseTimeout: time.Minute,
20	}
21	ctx = workflow.WithActivityOptions(ctx, options)
22
23	var result string
24	err := workflow.ExecuteActivity(ctx, ComposeGreeting, name).Get(ctx, &result)
25	if err != nil {
26		return "", err
27	}
28
29	return result, nil
30}
31
32// ComposeGreeting is the Activity definition.
33func ComposeGreeting(ctx context.Context, name string) (string, error) {
34	greeting := fmt.Sprintf("Hello %s!", name)
35	return greeting, nil
36}
37
38// --- Main Execution (Combined Worker and Starter) ---
39
40func main() {
41	// Create a Temporal Client to communicate with the local server
42	c, err := client.Dial(client.Options{
43		HostPort: client.DefaultHostPort,
44	})
45	if err != nil {
46		log.Fatalln("Unable to create Temporal client", err)
47	}
48	defer c.Close()
49
50	// Register and start the Worker
51	go func() {
52		w := worker.New(c, "hello-world-tasks", worker.Options{})
53
54		w.RegisterWorkflow(GreetingWorkflow)
55		w.RegisterActivity(ComposeGreeting)
56
57		err = w.Run(worker.InterruptCh())
58		if err != nil {
59			log.Fatalln("Unable to start Worker", err)
60		}
61	}()
62
63	// Execute the Workflow
64	workflowOptions := client.StartWorkflowOptions{
65		ID:        "hello_world_workflowID",
66		TaskQueue: "hello-world-tasks",
67	}
68
69	we, err := c.ExecuteWorkflow(context.Background(), workflowOptions, GreetingWorkflow, "Temporal")
70	if err != nil {
71		log.Fatalln("Unable to execute workflow", err)
72	}
73
74	// Get the result
75	var result string
76	err = we.Get(context.Background(), &result)
77	if err != nil {
78		log.Fatalln("Unable get workflow result", err)
79	}
80
81	fmt.Printf("\nWorkflow result: %s\n", result)
82}