Categorygithub.com/custom-app/protobson
modulepackage
1.0.1
Repository: https://github.com/custom-app/protobson.git
Documentation: pkg.go.dev

# README

protobson

GoDev Go Report Card

Description

protobson is a Go library consisting of a BSON codec for Protobuf messages that can be used with mongo-go-driver.

This library uses the second major version of the Go Protobuf API.

Main difference from original library is ability to set custom field naming - all you need is to make two functions to get document field name from proto field descriptor and versa.

Overview

Usage

Complete example can be seen in example directory

Below is a snippet making use of this codec by registering it with the MongoDB Go library:

package main

import (
	"log"
    "reflect"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo/options"
    "google.golang.org/protobuf/proto"

    "github.com/custom-app/protobson"
)

func main() {
    regBuilder := bson.NewRegistryBuilder()
    codec := protobson.NewCodec()

    msgType := reflect.TypeOf((*proto.Message)(nil)).Elem()
    registry := regBuilder.RegisterHookDecoder(msgType, codec).RegisterHookEncoder(msgType, codec).Build()

    opts := options.Client().SetRegistry(registry)
    opts.ApplyURI("mongodb://localhost:27017")
	client, err := mongo.Connect(context.Background(), opts)
	if err != nil {
		log.Panicln(err)
	}
	...
}

Note the use of RegisterHookDecoder and RegisterHookEncoder methods. Those ensure that given codec will be used to encode and decode values which type implement the interface. Since every Protobuf message implements the proto.Message interface, the codec will work with any message value.

Credits

This library is originally based on protomongo, part of the MIT-licensed dataform project by Tada Science, Inc.

# Packages

No description provided by the author
No description provided by the author

# Functions

NewCodec returns a new instance of a BSON codec for Protobuf messages.
WithFieldNamer - returns options with FieldNamer instance.
WithFieldNamerByJsonName makes FieldNamer Option with FieldNamerByJsonName instance.
WithFieldNamerByName makes FieldNamer Option with FieldNamerByName instance.
WithFieldNamerByNumber makes FieldNamer Option with FieldNamerByNumber instance.

# Variables

ErrNotImplementingProto occurs when value for decoding is not implementing proto.Message interface.

# Structs

FieldNamerByJsonName makes field name based on json name of field.
FieldNamerByName makes field name based on field name in proto spec.
FieldNamerByNumber makes field names based on field tag number.

# Interfaces

FieldNamer is used to build field name in document from its field descriptor.

# Type aliases

Option - functional option for protobufCodec.