git.zd.zone/hrpc/hrpc@v0.0.12/hrpc.go (about) 1 package hrpc 2 3 import ( 4 "context" 5 "time" 6 7 "git.zd.zone/hrpc/hrpc/codec" 8 "git.zd.zone/hrpc/hrpc/configs" 9 "git.zd.zone/hrpc/hrpc/filter" 10 "git.zd.zone/hrpc/hrpc/log" 11 "git.zd.zone/hrpc/hrpc/log/cls" 12 "git.zd.zone/hrpc/hrpc/option" 13 "git.zd.zone/hrpc/hrpc/plugin" 14 "git.zd.zone/hrpc/hrpc/server" 15 "git.zd.zone/hrpc/hrpc/tracer" 16 "git.zd.zone/hrpc/hrpc/utils/location" 17 "git.zd.zone/hrpc/hrpc/utils/uniqueid" 18 "google.golang.org/grpc/metadata" 19 ) 20 21 // NewServer is the entrance of the framwork 22 func NewServer(opts ...option.Option) (server.Server, error) { 23 var opt = option.DefaultOptions 24 for _, o := range opts { 25 o(&opt) 26 } 27 if err := opt.Valid(); err != nil { 28 return nil, err 29 } 30 31 // register server filters 32 for _, f := range opt.ServerFilters { 33 filter.Register(f.Name, f.Fn) 34 } 35 plugin.Register(uniqueid.New(), location.New(), configs.New( 36 opt.ConsulCenter.Address, 37 opt.ConsulCenter.DataCenter, 38 opt.ENV.String(), 39 opt.ConsulCenter.Token, 40 opt.ServerName, 41 )) 42 plugin.Register(opt.Plugins...) 43 if err := plugin.Setup(); err != nil { 44 return nil, err 45 } 46 47 // fixup the ID 48 opt.ID = uniqueid.String() 49 50 logOpt := log.Option{ 51 Environment: opt.ENV.String(), 52 StackSkip: opt.StackSkip, 53 } 54 if cls.Hook() != nil { 55 logOpt.Hooks = append(logOpt.Hooks, cls.Hook()) 56 } 57 log.With(logOpt) 58 59 // returns a new grpc server with desired options 60 return server.NewHRPC(&opt) 61 } 62 63 // BackgroundContext should be used to instead context.Context 64 func BackgroundContext() context.Context { 65 ctx := context.Background() 66 msg := codec.Message(ctx) 67 msg.WithServerName(server.Name()) 68 msg.WithNamespace(server.Environment().String()) 69 msg.WithRequestTimeout(time.Second * 5) 70 msg.WithTraceID(tracer.NewID(server.Name())) 71 ctx = metadata.NewOutgoingContext( 72 ctx, msg.Metadata(), 73 ) 74 return metadata.NewIncomingContext( 75 ctx, msg.Metadata(), 76 ) 77 } 78 79 // Go is a type of implemation of goroutine but it has panic reovery feature 80 func Go(ctx context.Context, fn func(ctx context.Context)) { 81 go func() { 82 defer func() { 83 if err := recover(); err != nil { 84 log.WithFields(ctx).Error(err) 85 } 86 }() 87 fn(ctx) 88 }() 89 }