autonats

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2020 License: MIT Imports: 17 Imported by: 0

README

Autonats

Build Status Go Report Card

Generate NATS client code and server handlers from Go interfaces.

Useful for projects with multiple services that share some source code.

Usage

Enable code generation for an interface
// Add the following comment to instruct Autonats
// to generate files for this interface:
//
// @nats:server User
type UserService interface {
  // Add as many methods in the interface
  //
  // Each method can take one or no parameters,
  // it can return one or no parameters, in addition to an error
  // 
  // Methods that do not return any values will be treated as 
  // fire and forget calls. Errors during transport will be logged
  // and the message would be considered as delivered as soon
  // as a server receives it regardless of the actual processing status.
  //
  
  // takes one param and returns one param + error
  GetById(id primitive.ObjectId) (*User, error)
 
  // takes no params
  GetAll() ([]*User, error)
  
  // takes no params, returns error only
  DeleteAll() error
 
  // takes nothing, returns nothing
  SendInvoices()
}
Run CLI tool

You can run the tool by downloading it from the releases page, or by using the docker image.

# CLI tool
$ autonats g 

# Docker
$ docker run -it --rm -v $(pwd):/root/ harbor.zyra.ca/public/autonats g

# TODO: upload to dockerhub
Use the generated code
Server handler
import (
  "github.com/nats-io/nats.go"
  "context"
)

var nc *natsgo.Connection // replace with a real connection
var server UserService // struct that implements the previously defined interface

_, err := NewUserHandler(context.TODO(), server, nc)

if err != nil {
  // the handler failed to subscribe with the provided NATS connection
  // handle the error
}

// server is up and running and is ready to process requests
// it will shut down automatically when context is done
Client code
import (
  "github.com/nats-io/nats.go"
  "log"
)

var nc *natsgo.Connection // replace with a real connection
l := log.New(...) // or any logger with Printf

// create client
client := NewUserClient(nc, l)

// use it as defined in the interface
user, err := GetById(...)

Documentation

Index

Constants

View Source
const DocPrefix = "@nats:"
View Source
const ENCODER = "AUTONATS_ENCODER"

Unique encoder id

Variables

This section is empty.

Functions

func ParseDir added in v0.3.0

func ParseDir(path string) (map[string]*ast.Package, error)

func Render added in v0.3.0

func Render(data *RenderData)

func SendRequest added in v0.3.0

func SendRequest(ctx context.Context, nc *nats.EncodedConn, subject string, in, out interface{}) error

Types

type Encoder added in v0.3.0

type Encoder struct{}

func (*Encoder) Decode added in v0.3.0

func (enc *Encoder) Decode(subject string, data []byte, vPtr interface{}) error

Implement (nats.Encoder).Decode

func (*Encoder) Encode added in v0.3.0

func (enc *Encoder) Encode(subject string, v interface{}) ([]byte, error)

Implement (nats.Encoder).Encode

type Function added in v0.3.0

type Function struct {
	Name    string
	Params  []*Param
	Results []*Param

	HandlerConcurrency int
	// contains filtered or unexported fields
}

func FuncFromType added in v0.3.0

func FuncFromType(fxField *ast.Field) *Function

type Handler added in v0.3.0

type Handler interface {
	Run(ctx context.Context) error // Subscribes to the queue and dispatches handler go-routines
	Shutdown()                     // Shuts down all handlers gracefully
}

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger for Service client

type Package added in v0.3.0

type Package struct {
	Services       []*Service
	Imports        map[string]string
	Name           string
	BaseDir        string
	OriginFileName string
	FileName       string
}

func PackageFromService added in v0.3.0

func PackageFromService(svc *Service) *Package

func (*Package) AddService added in v0.3.0

func (pkg *Package) AddService(service *Service)

type Param added in v0.3.0

type Param struct {
	Name, Type, TypePackage string
	Pointer, Array          bool
	RequiredImports         map[string]bool
}

func ParseParam added in v0.3.0

func ParseParam(f *ast.Field) *Param

type Parser

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

Parser object

func NewParser

func NewParser() *Parser

Creates a new parser with the provided config

func (*Parser) AddRawPackages added in v0.3.0

func (par *Parser) AddRawPackages(packages map[string]*ast.Package)

func (*Parser) ParseDir added in v0.3.0

func (par *Parser) ParseDir(path string) error

func (*Parser) Render added in v0.3.0

func (par *Parser) Render(outfile string, timeout int)

func (*Parser) Run

func (par *Parser) Run()

Runs the parser and outputs generated code to file

type ParserConfig

type ParserConfig struct {
	BaseDir        string // Directory containing interfaces to scan
	DefaultTimeout int    // Timeout for NATS requests
	OutputFileName string // Output file name
}

Parser config

type RenderData added in v0.3.0

type RenderData struct {
	PackageName, FileName, Path string
	Services                    []*Service
	Imports                     []string
	Timeout                     int
}

type Reply added in v0.3.0

type Reply struct {
	Data  []byte `json:"d,omitempty"`
	Error []byte `json:"error,omitempty"`
}

type Runner added in v0.3.0

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

func StartRunner added in v0.3.0

func StartRunner(ctx context.Context, nc *nats.Conn, subj, group string, concurrency int, handleFn func(msg *nats.Msg) (interface{}, error)) (*Runner, error)

func (*Runner) Shutdown added in v0.3.0

func (r *Runner) Shutdown() error

type Service added in v0.3.0

type Service struct {
	InterfaceID string
	Name        string
	Methods     []*Function
	Imports     map[string]string
	Basedir     string
	PackageName string
	FileName    string
}

func ServicesFromFile added in v0.3.0

func ServicesFromFile(pkgName, fileName string, file *ast.File) []*Service

func ServicesFromPkg added in v0.3.0

func ServicesFromPkg(v *ast.Package) []*Service

type ServiceConfig added in v0.3.0

type ServiceConfig struct {
	Name    string
	Timeout time.Duration
}

func ServiceConfigFromDoc added in v0.3.0

func ServiceConfigFromDoc(doc *ast.CommentGroup) ServiceConfig

Directories

Path Synopsis
cmd
api

Jump to

Keyboard shortcuts

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