Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 package streamclient | |
| 6 | |
| 7 import ( | |
| 8 "fmt" | |
| 9 "strings" | |
| 10 "sync" | |
| 11 ) | |
| 12 | |
| 13 var ( | |
| 14 // defaultRegistry is the default protocol registry. | |
| 15 defaultRegistry = &protocolRegistry{} | |
| 16 ) | |
| 17 | |
| 18 // protocolRegistry maps protocol prefix strings to their Client generator | |
| 19 // functions. | |
| 20 // | |
| 21 // This allows multiple Butler stream protocols (e.g., "unix:", "net.pipe:", | |
| 22 // etc.) to be parsed from string. | |
| 23 type protocolRegistry struct { | |
| 24 sync.Mutex | |
| 25 | |
| 26 // protocols is the set of registered protocols. Each client should regi ster | |
| 27 // via registerProtocol in its init() method. | |
| 28 protocols map[string]clientFactory | |
| 29 } | |
| 30 | |
| 31 func (r *protocolRegistry) register(name string, f clientFactory) { | |
| 32 r.Lock() | |
| 33 defer r.Unlock() | |
| 34 | |
| 35 if _, ok := r.protocols[name]; ok { | |
| 36 panic(fmt.Errorf("streamclient: protocol already registered for [%s]", name)) | |
| 37 } | |
| 38 if r.protocols == nil { | |
| 39 r.protocols = make(map[string]clientFactory) | |
| 40 } | |
| 41 r.protocols[name] = f | |
| 42 } | |
| 43 | |
| 44 // newClient invokes the protocol clientFactory generator for the | |
| 45 // supplied protocol/address string, returning the generated Client. | |
| 46 func (r *protocolRegistry) newClient(path string) (Client, error) { | |
| 47 parts := strings.SplitN(path, ":", 2) | |
| 48 params := "" | |
| 49 if len(parts) == 2 { | |
| 50 params = parts[1] | |
| 51 } | |
| 52 | |
| 53 r.Lock() | |
| 54 defer r.Unlock() | |
| 55 | |
| 56 if f, ok := r.protocols[parts[0]]; ok { | |
| 57 return f(params) | |
| 58 } | |
| 59 return nil, fmt.Errorf("streamclient: no protocol registered for [%s]", parts[0]) | |
| 60 } | |
| 61 | |
| 62 // registerProtocol registers a protocol with the default (global) protocol | |
| 63 // registry. | |
| 64 func registerProtocol(name string, f clientFactory) { | |
| 65 defaultRegistry.register(name, f) | |
|
iannucci
2015/11/12 22:44:25
mutex? or no need?
dnj
2015/11/13 20:17:15
Mutex is on a per-registry basis, so not needed he
| |
| 66 } | |
| OLD | NEW |