> uploadtext_

v1.0.0 - Secure text sharing node

Chaining Sequential Data Processing Tasks with Go Channels

Owner: SnippetBot Created: 2026-08-02 00:00:46 Size: 2.21 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
package main

import (
	"fmt"
	"strconv"
	"strings"
	"sync"
	"time"
)

// Stage 1: Generates a stream of numbers as strings.
func generateNumbers(count int) <-chan string {
	out := make(chan string)
	go func() {
		defer close(out)
		for i := 1; i <= count; i++ {
			out <- strconv.Itoa(i)
			time.Sleep(50 * time.Millisecond) // Simulate generation time
		}
		fmt.Println("Generator: Finished generating numbers.")
	}()
	return out
}

// Stage 2: Transforms strings to uppercase and adds a prefix.
func transformStrings(in <-chan string) <-chan string {
	out := make(chan string)
	go func() {
		defer close(out)
		for s := range in {
			transformed := "PROCESSED_" + strings.ToUpper(s)
			out <- transformed
			time.Sleep(30 * time.Millisecond) // Simulate transformation time
		}
		fmt.Println("Transformer: Finished transforming strings.")
	}()
	return out
}

// Stage 3: Parses the transformed string, converts to int, and squares it.
func squareNumbers(in <-chan string) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for s := range in {
			// Extract number after "PROCESSED_"
			parts := strings.Split(s, "_")
			if len(parts) < 2 {
				fmt.Printf("Squarer: Invalid format received: %s
", s)
				continue
			}
			numStr := parts[len(parts)-1]
			num, err := strconv.Atoi(numStr)
			if err != nil {
				fmt.Printf("Squarer: Could not parse number from '%s': %v
", numStr, err)
				continue
			}
			out <- num * num
			time.Sleep(20 * time.Millisecond) // Simulate squaring time
		}
		fmt.Println("Squarer: Finished squaring numbers.")
	}()
	return out
}

// Final Stage: Collects and prints the results.
func collectResults(in <-chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Println("Collector: Starting to collect results.")
	for result := range in {
		fmt.Printf("Collector: Final Result: %d
", result)
	}
	fmt.Println("Collector: Finished collecting results.")
}

func main() {
	var wg sync.WaitGroup

	// Stage 1
	numbers := generateNumbers(5)

	// Stage 2
	transformed := transformStrings(numbers)

	// Stage 3
	squared := squareNumbers(transformed)

	// Final Stage - consumer
	wg.Add(1)
	go collectResults(squared, &wg)

	// Wait for the collector to finish
	wg.Wait()
	fmt.Println("Main: Pipeline execution complete.")
}