This is an explanation of the video content.
 用技术延续对ACG的热爱
72

 |   | 

Go实现流水线任务

pipeline-go PkgGoDev

This package allows you to use the Pipeline pattern in your processes, and it’s built upon the Chain of Responsibility (CoR) design pattern.

CoR is a behavioral design pattern that processes given data through a series of handlers. When a request reaches the pipe class, it processes the data and then forwards it to the next handler. The principle behind this pattern is straightforward.

pipeline

In summary, the Pipeline is a design pattern tailored for managing sequential modifications to an object. Imagine it as an assembly line: each station represents a pipe, and by the end of the line, you’re left with a transformed object.

Install

go get github.com/izniburak/pipeline-go

Examples

package main

import (
	"fmt"
	"strings"
	"github.com/izniburak/pipeline-go"
)

type UpperCasePipe struct{}

func (u *UpperCasePipe) Handle(value pipeline.PipeValue, next pipeline.PipeNext) pipeline.PipeValue {
	// get value
	text := value.(string)
	capitalized := strings.ToUpper(text)
	return next(capitalized)
}

type TrimSpacePipe struct{}

func (t *TrimSpacePipe) Handle(value pipeline.PipeValue, next pipeline.PipeNext) pipeline.PipeValue {
	// get value
	text := value.(string)
	trimmed := strings.Trim(text, " ")
	return next(trimmed)
}

func main() {
	text := "   buki.dev   "

	pipes := []pipeline.PipeInterface{
		new(UpperCasePipe),
		new(TrimSpacePipe),
	}
	result := pipeline.Send(text).Through(pipes).ThenReturn()

	fmt.Println(result) // BUKI.DEV
}

Contributing

  1. Fork the repo (https://github.com/izniburak/pipeline-go/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am ‘Add some feature’)
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

  • izniburak İzni Burak Demirtaş - creator, maintainer

License

The MIT License (MIT) - see license.md for more details

核心源码 pipeline.go

package pipeline

type PipeValue interface{}
type PipeNext func(PipeValue) PipeValue

type PipeInterface interface {
	Handle(PipeValue, PipeNext) PipeValue
}

type Pipeline struct {
	value PipeValue
	pipes []PipeInterface
}

func Send(value interface{}) *Pipeline {
	return &Pipeline{value: value}
}

func (p *Pipeline) Through(pipes []PipeInterface) *Pipeline {
	p.pipes = pipes
	return p
}

func (p *Pipeline) Then(destination PipeNext) PipeValue {
	carry := p.carry()
	stack := destination
	for i := len(p.pipes) - 1; i >= 0; i-- {
		stack = carry(stack, p.pipes[i])
	}
	return stack(p.value)
}

func (p *Pipeline) ThenReturn() PipeValue {
	return p.Then(func(value PipeValue) PipeValue {
		return value
	})
}

func (p *Pipeline) carry() func(PipeNext, PipeInterface) PipeNext {
	return func(stack PipeNext, pipe PipeInterface) PipeNext {
		return func(value PipeValue) PipeValue {
			return pipe.Handle(value, stack)
		}
	}
}

72 服务端 ↦ Go开发技巧 __ 389 字
 Go开发技巧 #16