This example demonstrates how to use conditional logic within a workflow using the ThenStepIf builder method.
The workflow processes an input value and optionally performs operations based on flags provided in the input.
It showcases:
- Conditional Execution: Using
ThenStepIfto execute steps only when a condition is met. - State Management: Storing flags in the workflow context state for use in conditions.
- Default Values: Providing default output values when a step is skipped.
-
Setup Step (
setup):- Input:
ConditionalInput(Value, EnableDoubling, EnableFormatting) - Action: Extracts
EnableDoublingandEnableFormattingflags and stores them in the workflow state (ctx.State). PassesValueto the next step. - Output:
DoubleInput(Value)
- Input:
-
Double Step (
double) - Conditional:- Condition: Checks if
enable_doublingis true in state. - Action: Multiples the value by 2.
- Default: If skipped, returns a default object with
Value: 0andDoubled: false. - Output:
DoubleOutput(Value, Doubled, Message)
- Condition: Checks if
-
Format Step (
conditional_format) - Conditional:- Condition: Checks if the output value from the
doublestep is greater than 10. - Action: Formats the result into a string.
- Output:
ConditionalFormatOutput(Value, Formatted, Doubled)
- Condition: Checks if the output value from the
graph TD
Input[ConditionalInput] --> Setup[Setup Step]
Setup --> CheckDouble{Enable Doubling?}
CheckDouble -->|Yes| Double[Double Step]
CheckDouble -->|No| DefaultDouble[Default Output]
Double --> CheckFormat{Enable Formatting?}
DefaultDouble --> CheckFormat
CheckFormat -->|Yes| Format[Format Step]
CheckFormat -->|No| End[End]
Format --> Output[ConditionalFormatOutput]
-
Start the Server:
go run main/main.go
-
Trigger the Workflow (With Doubling):
curl -X POST http://localhost:3000/api/v1/workflows/conditional \ -H "Content-Type: application/json" \ -d '{"value": 10, "enable_doubling": true, "enable_formatting": true}'
-
Trigger the Workflow (Without Doubling):
curl -X POST http://localhost:3000/api/v1/workflows/conditional \ -H "Content-Type: application/json" \ -d '{"value": 10, "enable_doubling": false, "enable_formatting": true}'
The ThenStepIf method takes the step, a condition function, and a default value.
// Define condition
shouldDouble := func(ctx *gorkflow.StepContext) (bool, error) {
var enable bool
ctx.State.Get("enable_doubling", &enable)
return enable, nil
}
// Add to workflow
builder.ThenStepIf(NewDoubleStep(), shouldDouble, doubleDefault)The SetupStep puts data into the context state, which is accessible by condition functions (and other steps).
ctx.State.Set("enable_doubling", input.EnableDoubling)Conditions can also inspect the output of previous steps using ctx.Outputs.
shouldFormat := func(ctx *gorkflow.StepContext) (bool, error) {
var doubleOut DoubleOutput
if err := ctx.Outputs.GetOutput("double", &doubleOut); err != nil {
return false, nil
}
return doubleOut.Value > 10, nil
}