RegisterName will create a service for the given rcvr type under the given name. When no methods on the given rcvr match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is created and added to the service collection this server instance serves.
(name string, rcvr interface{})
| 77 | // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is |
| 78 | // created and added to the service collection this server instance serves. |
| 79 | func (s *Server) RegisterName(name string, rcvr interface{}) error { |
| 80 | if s.services == nil { |
| 81 | s.services = make(serviceRegistry) |
| 82 | } |
| 83 | |
| 84 | svc := new(service) |
| 85 | svc.typ = reflect.TypeOf(rcvr) |
| 86 | rcvrVal := reflect.ValueOf(rcvr) |
| 87 | |
| 88 | if name == "" { |
| 89 | return fmt.Errorf("no service name for type %s", svc.typ.String()) |
| 90 | } |
| 91 | if !isExported(reflect.Indirect(rcvrVal).Type().Name()) { |
| 92 | return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name()) |
| 93 | } |
| 94 | |
| 95 | methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ) |
| 96 | |
| 97 | // already a previous service register under given sname, merge methods/subscriptions |
| 98 | if regsvc, present := s.services[name]; present { |
| 99 | if len(methods) == 0 && len(subscriptions) == 0 { |
| 100 | return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) |
| 101 | } |
| 102 | for _, m := range methods { |
| 103 | regsvc.callbacks[formatName(m.method.Name)] = m |
| 104 | } |
| 105 | for _, s := range subscriptions { |
| 106 | regsvc.subscriptions[formatName(s.method.Name)] = s |
| 107 | } |
| 108 | return nil |
| 109 | } |
| 110 | |
| 111 | svc.name = name |
| 112 | svc.callbacks, svc.subscriptions = methods, subscriptions |
| 113 | |
| 114 | if len(svc.callbacks) == 0 && len(svc.subscriptions) == 0 { |
| 115 | return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) |
| 116 | } |
| 117 | |
| 118 | s.services[svc.name] = svc |
| 119 | return nil |
| 120 | } |
| 121 | |
| 122 | // serveRequest will reads requests from the codec, calls the RPC callback and |
| 123 | // writes the response to the given codec. |