bishamon

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2024 License: Apache-2.0 Imports: 9 Imported by: 1

README

bishamon

Пакет позволяет редактировать message proto с помощью extension. Как это работает:

  1. Создаем message proto аля example.proto.
  2. Создаём extension message аля sensitive.proto. Если нужно работать с мапами, то добавляем поле с типом repeated string в нашем extension message (типа такого repeated string map_keys_to_redact = 1;). В нём мы будем хранить поля, с которыми надо будет работать в мапе. Т.к. мы сами задаём это поле, то мы всегда знаем, что сгенерирует protoc (в .pb.go файле будет присутствовать метод, который нам нужен для работы с мапой, он будет иметь вид Get + название поля в camelCase, в нашем случае это будет GetMapKeysToRedact).
  3. Добавляем extension к message proto:
    1. Добавляем import "sensitive.proto";
    2. У полей, которые мы хотим редактировать, добавляем [(sensitive) = {}]. Если это мапа и мы хотим редактировать конкретные ключи, то добавляем [(sensitive) = {map_keys_to_redact:["phone", "email"]}], т.е. перечисляем поля, которые надо редактировать.
  4. Генерируем .go файлы с помощью protoc.
  5. В sensitive.pb.go мы можем найти переменную, которая будет начинаться с E_ + название нашего extension message в camelCase. В нашем случае это E_Sensitive. Эту переменную надо передать в редактор, чтобы он смог определять, какие поля надо редактировать. Так же в этом файле мы можем найти функцию, определение которой нам надо передать в редактор, если мы хотим работать с мапой. Т.к. в нашем случае это GetMapKeysToRedact, то мы на основе неё можем собрать функцию, которая будет удовлетворять типу FieldsFromMapFunc и возвращать список ключей для редактирования мапы. Пример можно посмотреть в functions.go в функции CommonFieldsFromMapFunc.
  6. Создаём редактор redactor.go через NewRedactor, в который передаём E_Sensitive и опции для редактирования. Есть уже готовый вариант редактора, который удаляет все помеченные поля - NewCleanRedactor.
  7. У редактора есть два метода:
    1. Redact - редактирует само сообщение.
    2. RedactClone - редактирует копию сообщения и возвращает её.
  8. Пример использования можно посмотреть в redactor_test.go.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ClearFieldFunc = func(message protoreflect.Message, fieldDescriptor protoreflect.FieldDescriptor) error {
		message.Clear(fieldDescriptor)
		return nil
	}

	ClearMapFunc = func(valueMap protoreflect.Map, mapKey protoreflect.MapKey, _ protoreflect.Value) error {
		valueMap.Clear(mapKey)
		return nil
	}

	ClearListFunc = func(list protoreflect.List) error {
		list.Truncate(0)
		return nil
	}

	CommonFieldsFromMapFunc = func(ext any) map[string]struct{} {
		extNeeded, ok := ext.(interface {
			GetMapKeysToRedact() []string
		})
		if !ok || len(extNeeded.GetMapKeysToRedact()) == 0 {
			return nil
		}

		return lilith.ArrayToMapValues(extNeeded.GetMapKeysToRedact())
	}
)
View Source
var (
	ErrInvalidRedactorArgs = errors.New("invalid args")
)

Functions

This section is empty.

Types

type FieldsFromMapFunc

type FieldsFromMapFunc func(ext any) map[string]struct{}

type RedactFieldFunc

type RedactFieldFunc func(message protoreflect.Message, fd protoreflect.FieldDescriptor) error

type RedactListFunc

type RedactListFunc func(list protoreflect.List) error

type RedactMapFunc

type RedactMapFunc func(valueMap protoreflect.Map, mapKey protoreflect.MapKey, value protoreflect.Value) error

type Redactor

type Redactor struct {
	// contains filtered or unexported fields
}

func NewClearRedactor

func NewClearRedactor(extInfo *protoimpl.ExtensionInfo, opts ...RedactorOption) (*Redactor, error)

func NewRedactor

func NewRedactor(
	extInfo *protoimpl.ExtensionInfo,
	opts ...RedactorOption,
) (*Redactor, error)

func (*Redactor) Redact

func (r *Redactor) Redact(msg proto.Message) error

func (*Redactor) RedactClone

func (r *Redactor) RedactClone(msg proto.Message) (proto.Message, error)

type RedactorFuncs

type RedactorFuncs struct {
	// contains filtered or unexported fields
}

type RedactorOption

type RedactorOption func(*Redactor)

func WithFieldsFromMapFunc

func WithFieldsFromMapFunc(fieldsFromMapFunc FieldsFromMapFunc) RedactorOption

func WithRedactFuncs

func WithRedactFuncs(redactFuncs ...RedactFieldFunc) RedactorOption

func WithRedactListFuncs

func WithRedactListFuncs(redactListFuncs ...RedactListFunc) RedactorOption

func WithRedactMapFuncs

func WithRedactMapFuncs(redactMapFuncs ...RedactMapFunc) RedactorOption

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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