Help us shape the future of Go! Take the 2026 Go Developer Survey

gohooks

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2019 License: MIT Imports: 4 Imported by: 0

README

Golang Hooks

参考 wordpress 的 hooks 机制实现的 golang hooks(the wordpress filter/action system in golang)

非线程安全

Installation

$ go get -u github.com/niqingyang/gohooks

Quick start

  1. 获取 hooks 全局单例实例
package instance

import "github.com/niqingyang/gohooks"

func main()  {
	hooks := gohooks.Instance()
	// ...
}
  1. 获取一个新的 hooks 实例
package instance

import "github.com/niqingyang/gohooks"

func main()  {
	hooks := gohooks.NewInstance()
	// ...
}
  1. 添加 Filter
package filter

import (
	"fmt"
	"github.com/niqingyang/gohooks"
)

func main()  {
	hooks := gohooks.Instance()

	hooks.AddFilter("increase", func(data interface{}, params ...interface{}) (interface{}, error) {
    
    		switch data := data.(type) {
    		case int:
    			return data + 1, nil
    		}
    
    		return data, nil
	}, gohooks.DefaultPriority)
    
	data, e :=hooks.ApplyFilter("increase", 1)
    
	fmt.Println(data, e)
}
  1. 添加 Action
package main

import (
	"fmt"
	"github.com/niqingyang/gohooks"
)

func main() {
	hooks := gohooks.Instance()

	hooks.AddAction("test", func(params ...interface{}) {

		fmt.Println(params)

	}, gohooks.DefaultPriority)

	hooks.DoAction("test", 1, 2, 3, 4)
}
  1. 其他接口
// 获取全局 hooks 单例
gohooks.Instance()
// 获取新的 hooks 实例
gohooks.NewInstance()
// 添加 Filter
hooks.AddFilter(tag, filter, priority)
// 移除 Filter
hooks.RemoveFilter(tag, filter, priority)
// 移除所有 Filter
hooks.RemoveAllFilter(tag, priority)
// 添加 Filter
hooks.HasFilter(tag, filter)
// 添加 Action
hooks.AddAction(tag, action, priority)
// 移除 Action
hooks.RemoveAction(tag, action, priority)
// 移除所有 Action
hooks.RemoveAllAction(tag, priority)
// 添加 Action
hooks.HasAction(tag, action)

Documentation

Index

Constants

View Source
const AllPriority = 0

移除所有 Filter 和 Action 时用到的排序值

View Source
const DefaultPriority = 10

默认排序

Variables

This section is empty.

Functions

func Instance

func Instance() *hooks

获取 hooks 的单例

func NewInstance

func NewInstance() *hooks

新建一个 hooks 实例

Types

type Action

type Action func(...interface{})

Action 接口

type Filter

type Filter func(interface{}, ...interface{}) (interface{}, error)

Filter 接口 - 对输入的参数进行过滤,返回值将作为下一个 Filter 的第一个入参

Directories

Path Synopsis
example
action command
filter command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL