New creates a new Client to the Asterisk ARI NATS/RabbitMQ proxy.
(ctx context.Context, opts ...OptionFunc)
| 216 | |
| 217 | // New creates a new Client to the Asterisk ARI NATS/RabbitMQ proxy. |
| 218 | func New(ctx context.Context, opts ...OptionFunc) (*Client, error) { |
| 219 | ctx, cancel := context.WithCancel(ctx) |
| 220 | |
| 221 | c := &Client{ |
| 222 | appName: os.Getenv("ARI_APPLICATION"), |
| 223 | core: &core{ |
| 224 | cluster: cluster.New(), |
| 225 | clusterMaxAge: DefaultClusterMaxAge, |
| 226 | inputBufferLength: DefaultInputBufferLength, |
| 227 | log: log15.New(), |
| 228 | prefix: "ari.", |
| 229 | requestTimeout: DefaultRequestTimeout, |
| 230 | uri: "nats://localhost:4222", |
| 231 | }, |
| 232 | cancel: cancel, |
| 233 | } |
| 234 | c.log.SetHandler(log15.DiscardHandler()) |
| 235 | |
| 236 | // Load environment-based configurations |
| 237 | if os.Getenv("MESSAGEBUS_URL") != "" { |
| 238 | c.core.uri = os.Getenv("MESSAGEBUS_URL") |
| 239 | } else if os.Getenv("NATS_URI") != "" { //backward compatibility |
| 240 | c.core.uri = os.Getenv("NATS_URI") |
| 241 | } |
| 242 | |
| 243 | // Load explicit configurations |
| 244 | for _, opt := range opts { |
| 245 | opt(c) |
| 246 | } |
| 247 | |
| 248 | // Start the core, if it is not already started |
| 249 | err := c.core.Start() |
| 250 | if err != nil { |
| 251 | return nil, eris.Wrap(err, "failed to start core") |
| 252 | } |
| 253 | |
| 254 | // Create the bus |
| 255 | c.bus = bus.New(c.core.prefix, c.core.mbus, c.core.log) |
| 256 | |
| 257 | // Call Close whenever the context is closed |
| 258 | go func() { |
| 259 | <-ctx.Done() |
| 260 | if !c.closed { |
| 261 | // Only wait the grace period if we have not |
| 262 | // already been closed. |
| 263 | <-time.After(ClosureGracePeriod) |
| 264 | } |
| 265 | |
| 266 | c.Close() |
| 267 | }() |
| 268 | |
| 269 | return c, nil |
| 270 | } |
| 271 | |
| 272 | // New returns a new client from the existing one. The new client will have a |
| 273 | // separate event bus and lifecycle, allowing the closure of all subscriptions |