micro.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package micro
  2. import (
  3. "context"
  4. "git.nspix.com/golang/micro/gateway/http"
  5. "git.nspix.com/golang/micro/gateway/rpc"
  6. "git.nspix.com/golang/micro/registry"
  7. )
  8. const (
  9. EnvironmentDocker string = "docker"
  10. EnvironmentHost = "host"
  11. )
  12. type (
  13. applicationKey struct {
  14. }
  15. HandleOptions struct {
  16. DisableRpc bool //禁用RPC功能
  17. DisableHttp bool //禁用HTTP功能
  18. HttpPath string //重定向HTTP路由
  19. HttpMethod string //HTTP路径
  20. }
  21. HandleOption func(o *HandleOptions)
  22. HandleFunc func(ctx Context) (err error)
  23. Application interface {
  24. Node() *registry.ServiceNode //获取节点信息
  25. HttpServe() *http.Server //获取HTTP实例
  26. RPCServe() *rpc.Server //获取RPC实例
  27. PeekService(name string) ([]*registry.ServiceNode, error) //选择一个服务
  28. Handle(method string, cb HandleFunc, opts ...HandleOption) //注册一个处理器
  29. NewRequest(name, method string, body interface{}) (req *Request, err error) //创建一个rpc请求
  30. Environment() string
  31. }
  32. Server interface {
  33. Start(ctx context.Context) (err error)
  34. Stop() (err error)
  35. }
  36. )
  37. var (
  38. contextKey = applicationKey{}
  39. )
  40. func FromContext(ctx context.Context) Application {
  41. if v := ctx.Value(contextKey); v != nil {
  42. return v.(Application)
  43. }
  44. return nil
  45. }
  46. func WithContext(ctx context.Context, app Application) context.Context {
  47. return context.WithValue(ctx, contextKey, app)
  48. }