Last active
December 15, 2016 17:28
-
-
Save korya/bfcd008387d5fd4a7d277d954a90cbd8 to your computer and use it in GitHub Desktop.
An example demonstrating basic service registry implemented in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Go play example: https://play.golang.org/p/5eoIRYy5Bn | |
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
type Policy interface { | |
IsAllowed() bool | |
} | |
type YesPolicy struct {} | |
func (p YesPolicy) IsAllowed() bool { | |
fmt.Printf("YesPolicy!\n") | |
return true | |
} | |
type NoPolicy struct {} | |
func (p NoPolicy) IsAllowed() bool { | |
fmt.Printf("NoPolicy...\n") | |
return false | |
} | |
type Authenticator struct { | |
AuthPolicy Policy | |
} | |
func (a Authenticator) Authenticate() { | |
p := a.AuthPolicy | |
pt := reflect.TypeOf(p) | |
var ptt reflect.Type | |
if pt.Kind() == reflect.Ptr { | |
ptt = pt | |
pt = pt.Elem() | |
} | |
fmt.Printf(" Authenticate: policy object=%-10p\n", p) | |
fmt.Printf(" : policy type=%20s [%p]\n", pt, pt) | |
if ptt != nil { | |
fmt.Printf(" : policy *type=%20s [%p]\n", ptt, ptt) | |
} | |
} | |
func main() { | |
fmt.Printf("Hard-coded use of policies:\n") | |
Authenticator{&YesPolicy{}}.Authenticate() | |
Authenticator{&NoPolicy{}}.Authenticate() | |
fmt.Printf("\n======\n\n") | |
policyType := reflect.TypeOf((*Policy)(nil)).Elem() | |
fmt.Printf("Policy interface type: %s [%p]\n\n", policyType, policyType) | |
serviceRegistry := map[reflect.Type]interface{}{ | |
policyType: &YesPolicy{}, | |
} | |
fmt.Printf("Service Registry: %v\n\n", serviceRegistry) | |
fmt.Printf("Use of policies via service regsitry:\n") | |
Authenticator{serviceRegistry[policyType].(Policy)}.Authenticate() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hard-coded use of policies: | |
Authenticate: policy object=0x196adc | |
: policy type= main.YesPolicy [0x1026a0] | |
: policy *type= *main.YesPolicy [0x100b60] | |
Authenticate: policy object=0x196adc | |
: policy type= main.NoPolicy [0x102640] | |
: policy *type= *main.NoPolicy [0x100b00] | |
====== | |
Policy interface type: main.Policy [0x101520] | |
Service Registry: map[main.Policy:0x196adc] | |
Use of policies via service regsitry: | |
Authenticate: policy object=0x196adc | |
: policy type= main.YesPolicy [0x1026a0] | |
: policy *type= *main.YesPolicy [0x100b60] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment