lunar

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2023 License: MIT Imports: 16 Imported by: 1

README

lunar

GoDoc CI codecov Release

Probably the most elegant ctrip apollo client in golang. This library has no third-party dependency.

Ctrip Apollo: https://github.com/ctripcorp/apollo

Default settings of lunar:

  • default namespace is application
  • default server is localhost:8080
  • default http client timeout is 90s

Require golang version >= 1.16 after v0.6.0

Usage

import "github.com/hyperjiang/lunar"

key := "foo"

app := lunar.New("myAppID", lunar.WithServer("localhost:8080"))

// get value of key in default namespace
app.GetValue(key)

// get value of key in namespace ns
app.GetValueInNamespace(key, "ns")

// get all the items in default namespace
app.GetItems()

// get all the items in namespace ns
app.GetItemsInNamespace("ns")

// get the content of ns namespace, if the format of ns is properties then will return json string
app.GetContent("ns")

// it will fetch items from apollo directly without reading local cache
app.GetNamespaceFromApollo("ns")

// watch changes of given namespaces
watchChan, errChan := app.Watch("ns1", "ns2", ...)

for {
	select {
	case n := <-watchChan:
		fmt.Println(n)
	case <-errChan:
		app.Stop() // stop watcher
		return
	}
}

Logging

lunar does not write logs by default, if you want to see logs for debugging, you can replace it with any logger which implements lunar.Logger interface.

lunar also provide a simple logger lunar.Printf which writes to stdout:

app := lunar.New("myAppID", lunar.WithServer("localhost:8080"), lunar.WithLogger(lunar.Printf))

Or you can use UseLogger method:

app.UseLogger(lunar.Printf)

Caching

lunar use memory cache by default, you can replace it with any cache which implements lunar.Cache interface.

lunar also provide a file cache lunar.FileCache which use files for caching:

app := lunar.New("myAppID")

app.UseCache(lunar.NewFileCache("myAppID", "/tmp"))

Enable Access Key

Starting from v1.6.0, apollo supports access key feature, you can use WithAccessKeySecret to set the secret:

app := lunar.New(
	"myAppID",
	lunar.WithServer("localhost:8080"),
	lunar.WithAccessKeySecret("mySecret"),
)

Documentation

Index

Constants

View Source
const (
	AuthorizationFormat = "Apollo %s:%s"
	Delimiter           = "\n"
)

Variables

Printf is a logger which wraps log.Printf

Functions

func GetFormat added in v0.3.0

func GetFormat(namespace string) string

GetFormat gets the format of namespace

func GetLocalIP added in v0.3.0

func GetLocalIP() string

GetLocalIP gets local ip

func IsProperties added in v0.3.0

func IsProperties(namespace string) bool

IsProperties checks if the format of namespace is properties

Types

type ApolloAPI

type ApolloAPI interface {
	GetCachedItems(namespace string) (Items, error)
	GetNamespace(namespace string, releaseKey string) (*Namespace, error)
	GetNotifications(ns Notifications) (Notifications, error)
}

ApolloAPI is the interface of apollo api

type ApolloClient

type ApolloClient struct {
	Options  // inherited options
	AppID    string
	Client   *http.Client
	ClientIP string
}

ApolloClient is the implementation of apollo client.

https://github.com/ctripcorp/apollo/wiki/%E5%85%B6%E5%AE%83%E8%AF%AD%E8%A8%80%E5%AE%A2%E6%88%B7%E7%AB%AF%E6%8E%A5%E5%85%A5%E6%8C%87%E5%8D%97

func NewApolloClient

func NewApolloClient(appID string, opts ...Option) *ApolloClient

NewApolloClient creates a apollo client

func (*ApolloClient) GetCachedItems

func (c *ApolloClient) GetCachedItems(namespace string) (Items, error)

GetCachedItems gets cached configs from apollo

func (*ApolloClient) GetNamespace

func (c *ApolloClient) GetNamespace(namespace string, releaseKey string) (*Namespace, error)

GetNamespace gets realtime namespace data from apollo

func (*ApolloClient) GetNotifications

func (c *ApolloClient) GetNotifications(ns Notifications) (Notifications, error)

GetNotifications gets notifications from apollo

type App

type App struct {
	Options           // inherited options
	ID      string    // app id
	Client  ApolloAPI // the apollo client

	Cache Cache
	// contains filtered or unexported fields
}

App represents a single application, an application has a unique app id and manage multiple namespaces.

func New

func New(appID string, opts ...Option) *App

New creates an application, user must specify the correct app id

func (*App) GetContent

func (app *App) GetContent(namespace string) (string, error)

GetContent gets the content of given namespace, if the format is properties then will return json string

func (*App) GetItems

func (app *App) GetItems() (Items, error)

GetItems gets all the items in default namespace

func (*App) GetItemsInNamespace

func (app *App) GetItemsInNamespace(namespace string) (Items, error)

GetItemsInNamespace gets all the items in given namespace.

func (*App) GetNamespaceFromApollo

func (app *App) GetNamespaceFromApollo(namespace string) (Items, error)

GetNamespaceFromApollo gets realtime data in given namespace from apollo and update local cache. This is the most basic method.

func (*App) GetReleaseKeys added in v0.2.0

func (app *App) GetReleaseKeys() map[string]string

GetReleaseKeys gets namespace and release key map

func (*App) GetValue

func (app *App) GetValue(key string) (string, error)

GetValue gets value of key in default namespace

func (*App) GetValueInNamespace

func (app *App) GetValueInNamespace(key string, namespace string) (string, error)

GetValueInNamespace gets value of key in given namespace

func (*App) Stop

func (app *App) Stop()

Stop stops watching

func (*App) UseCache

func (app *App) UseCache(c Cache) *App

UseCache sets the underlying cache

func (*App) UseClient

func (app *App) UseClient(client ApolloAPI) *App

UseClient sets the underlying apollo client

func (*App) UseLogger added in v0.4.4

func (app *App) UseLogger(l Logger) *App

UseLogger sets the logger

func (*App) Watch

func (app *App) Watch(namespaces ...string) (<-chan Notification, <-chan error)

Watch watches changes from apollo using long poll

type Cache

type Cache interface {
	GetItems(namespace string) Items
	SetItems(namespace string, items Items) error
	GetKeys() []string
	Delete(namespace string) error
	Drain()
}

Cache is the cache interface

type FileCache

type FileCache struct {
	AppID  string
	Folder string // root folder
	Perm   os.FileMode
	// contains filtered or unexported fields
}

FileCache is cache stored in files.

func NewFileCache

func NewFileCache(appID string, folder string) *FileCache

NewFileCache creates a FileCache

func (*FileCache) Delete

func (c *FileCache) Delete(namespace string) error

Delete deletes given namespace

func (*FileCache) Drain added in v0.2.0

func (c *FileCache) Drain()

Drain deletes the whole cache

func (*FileCache) GetItems

func (c *FileCache) GetItems(namespace string) Items

GetItems gets items from cache

func (*FileCache) GetKeys

func (c *FileCache) GetKeys() []string

GetKeys gets all the keys (namespaces)

func (*FileCache) SetItems

func (c *FileCache) SetItems(namespace string, items Items) error

SetItems sets items into cache

type Items

type Items map[string]string

Items is items under namespace

func (Items) Expand added in v0.4.1

func (items Items) Expand() interface{}

Expand expands dot-key items to nested map

func (Items) Get

func (items Items) Get(key string) string

Get gets value of given key

func (Items) String

func (items Items) String() string

String converts Items to json string

type Logger

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

Logger is logger interface

type LoggerFunc

type LoggerFunc func(string, ...interface{})

LoggerFunc is a bridge between Logger and any third party logger

func (LoggerFunc) Printf

func (f LoggerFunc) Printf(msg string, args ...interface{})

Printf implements Logger interface

type Lunar

type Lunar interface {
	GetValue(key string) (string, error)
	GetValueInNamespace(key string, namespace string) (string, error)
	GetItems() (Items, error)
	GetItemsInNamespace(namespace string) (Items, error)
	GetContent(namespace string) (string, error)
	GetReleaseKeys() map[string]string // key: namespace, value: release key
}

Lunar is the interface of lunar

type MemoryCache

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

MemoryCache is cache stored in memory, it's the default cache for use

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(namespace string) error

Delete deletes given namespace

func (*MemoryCache) Drain added in v0.2.0

func (c *MemoryCache) Drain()

Drain deletes the whole cache

func (*MemoryCache) GetItems

func (c *MemoryCache) GetItems(namespace string) Items

GetItems gets items from cache

func (*MemoryCache) GetKeys

func (c *MemoryCache) GetKeys() []string

GetKeys gets all the keys (namespaces)

func (*MemoryCache) SetItems

func (c *MemoryCache) SetItems(namespace string, items Items) error

SetItems sets items into cache

type Namespace

type Namespace struct {
	AppID      string `json:"appId"`
	Cluster    string `json:"cluster"`
	Name       string `json:"namespaceName"`
	Items      Items  `json:"configurations"`
	ReleaseKey string `json:"releaseKey"`
}

Namespace is apollo namespace data

type Node added in v0.4.0

type Node struct {
	Name     string
	Value    string // value only makes sense in leaf
	Children []*Node
}

Node is a tree node

func (*Node) AddChildren added in v0.4.0

func (node *Node) AddChildren(children ...*Node)

AddChildren adds children node if it's not existing

func (*Node) GetChild added in v0.4.0

func (node *Node) GetChild(name string) *Node

GetChild gets a child by its name

func (*Node) IsLeaf added in v0.4.0

func (node *Node) IsLeaf() bool

IsLeaf returns true if the node is a leaf

func (*Node) ToMap added in v0.4.0

func (node *Node) ToMap() interface{}

ToMap converts to map

type Notification

type Notification struct {
	Namespace      string `json:"namespaceName"`
	NotificationID int    `json:"notificationId"`
}

Notification is the definition of notification

type Notifications

type Notifications []Notification

Notifications is a set of notifications

func (Notifications) String

func (ns Notifications) String() string

String converts Notifications to json string

type Option

type Option func(*Options)

Option is for setting options

func WithAccessKeySecret added in v0.5.0

func WithAccessKeySecret(secret string) Option

WithAccessKeySecret sets access key secret

func WithClientTimeout

func WithClientTimeout(timeout time.Duration) Option

WithClientTimeout sets client timeout

func WithCluster

func WithCluster(cluster string) Option

WithCluster sets apollo cluster

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets logger

func WithLongPollInterval

func WithLongPollInterval(interval time.Duration) Option

WithLongPollInterval sets long poll interval

func WithServer

func WithServer(server string) Option

WithServer sets apollo server address

type Options

type Options struct {
	Server           string
	Cluster          string
	AccessKeySecret  string
	Logger           Logger
	ClientTimeout    time.Duration
	LongPollInterval time.Duration
}

Options is common options

func NewOptions

func NewOptions(opts ...Option) Options

NewOptions creates options with defaults

Jump to

Keyboard shortcuts

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