fix lint check (#746)

pull/747/head
Tony Chen 4 years ago committed by GitHub
parent 18752bf0ec
commit f86c91849b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      .github/workflows/go.yml
  2. 4
      cmd/kratos/internal/base/repo.go
  3. 2
      config/config.go
  4. 1
      config/reader.go
  5. 2
      encoding/json/json.go
  6. 32
      errors/codes.go
  7. 3
      internal/host/host.go
  8. 2
      log/helper.go
  9. 5
      log/nop.go
  10. 4
      middleware/status/status.go
  11. 4
      registry/registry.go
  12. 21
      transport/grpc/client.go
  13. 4
      transport/grpc/context.go
  14. 12
      transport/grpc/resolver/discovery/builder.go
  15. 20
      transport/grpc/server.go

@ -24,6 +24,11 @@ jobs:
- name: Test - name: Test
run: go test -v ./... run: go test -v ./...
- name: Lint
run: |
go get golang.org/x/lint/golint
golint ./...
- name: Kratos - name: Kratos
run: | run: |
cd cmd/kratos cd cmd/kratos

@ -24,12 +24,14 @@ func NewRepo(url string) *Repo {
} }
} }
// Path returns the repository cache path.
func (r *Repo) Path() string { func (r *Repo) Path() string {
start := strings.LastIndex(r.url, "/") start := strings.LastIndex(r.url, "/")
end := strings.LastIndex(r.url, ".git") end := strings.LastIndex(r.url, ".git")
return path.Join(r.home, r.url[start+1:end]) return path.Join(r.home, r.url[start+1:end])
} }
// Pull fetchs the repository from remote url.
func (r *Repo) Pull(ctx context.Context, url string) error { func (r *Repo) Pull(ctx context.Context, url string) error {
repo, err := git.PlainOpen(r.Path()) repo, err := git.PlainOpen(r.Path())
if err != nil { if err != nil {
@ -48,6 +50,7 @@ func (r *Repo) Pull(ctx context.Context, url string) error {
return err return err
} }
// Clone clones the repository to cache path.
func (r *Repo) Clone(ctx context.Context) error { func (r *Repo) Clone(ctx context.Context) error {
if _, err := os.Stat(r.Path()); !os.IsNotExist(err) { if _, err := os.Stat(r.Path()); !os.IsNotExist(err) {
return r.Pull(ctx, r.url) return r.Pull(ctx, r.url)
@ -59,6 +62,7 @@ func (r *Repo) Clone(ctx context.Context) error {
return err return err
} }
// CopyTo copies the repository to project path.
func (r *Repo) CopyTo(ctx context.Context, to string, modPath string, ignores []string) error { func (r *Repo) CopyTo(ctx context.Context, to string, modPath string, ignores []string) error {
if err := r.Clone(ctx); err != nil { if err := r.Clone(ctx); err != nil {
return err return err

@ -8,6 +8,8 @@ import (
"time" "time"
"github.com/go-kratos/kratos/v2/encoding" "github.com/go-kratos/kratos/v2/encoding"
// init json encoder
_ "github.com/go-kratos/kratos/v2/encoding/json"
"github.com/go-kratos/kratos/v2/log" "github.com/go-kratos/kratos/v2/log"
) )

@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"strings" "strings"
_ "github.com/go-kratos/kratos/v2/encoding/json"
"github.com/imdario/mergo" "github.com/imdario/mergo"
) )

@ -22,8 +22,6 @@ var (
UnmarshalOptions = protojson.UnmarshalOptions{ UnmarshalOptions = protojson.UnmarshalOptions{
DiscardUnknown: true, DiscardUnknown: true,
} }
typeProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem()
) )
func init() { func init() {

@ -15,6 +15,8 @@ func Cancelled(reason, format string, a ...interface{}) error {
} }
} }
// IsCancelled determines if err is an error which indicates a cancelled error.
// It supports wrapped errors.
func IsCancelled(err error) bool { func IsCancelled(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 1 return se.Code == 1
@ -32,6 +34,8 @@ func Unknown(reason, format string, a ...interface{}) error {
} }
} }
// IsUnknown determines if err is an error which indicates a unknown error.
// It supports wrapped errors.
func IsUnknown(err error) bool { func IsUnknown(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 2 return se.Code == 2
@ -49,6 +53,8 @@ func InvalidArgument(reason, format string, a ...interface{}) error {
} }
} }
// IsInvalidArgument determines if err is an error which indicates an invalid argument error.
// It supports wrapped errors.
func IsInvalidArgument(err error) bool { func IsInvalidArgument(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 3 return se.Code == 3
@ -66,6 +72,8 @@ func DeadlineExceeded(reason, format string, a ...interface{}) error {
} }
} }
// IsDeadlineExceeded determines if err is an error which indicates a deadline exceeded error.
// It supports wrapped errors.
func IsDeadlineExceeded(err error) bool { func IsDeadlineExceeded(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 4 return se.Code == 4
@ -83,6 +91,8 @@ func NotFound(reason, format string, a ...interface{}) error {
} }
} }
// IsNotFound determines if err is an error which indicates a not found error.
// It supports wrapped errors.
func IsNotFound(err error) bool { func IsNotFound(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 5 return se.Code == 5
@ -100,6 +110,8 @@ func AlreadyExists(reason, format string, a ...interface{}) error {
} }
} }
// IsAlreadyExists determines if err is an error which indicates a already exsits error.
// It supports wrapped errors.
func IsAlreadyExists(err error) bool { func IsAlreadyExists(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 6 return se.Code == 6
@ -117,6 +129,8 @@ func PermissionDenied(reason, format string, a ...interface{}) error {
} }
} }
// IsPermissionDenied determines if err is an error which indicates a permission denied error.
// It supports wrapped errors.
func IsPermissionDenied(err error) bool { func IsPermissionDenied(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 7 return se.Code == 7
@ -135,6 +149,8 @@ func ResourceExhausted(reason, format string, a ...interface{}) error {
} }
} }
// IsResourceExhausted determines if err is an error which indicates a resource exhausted error.
// It supports wrapped errors.
func IsResourceExhausted(err error) bool { func IsResourceExhausted(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 8 return se.Code == 8
@ -153,6 +169,8 @@ func FailedPrecondition(reason, format string, a ...interface{}) error {
} }
} }
// IsFailedPrecondition determines if err is an error which indicates a failed precondition error.
// It supports wrapped errors.
func IsFailedPrecondition(err error) bool { func IsFailedPrecondition(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 9 return se.Code == 9
@ -171,6 +189,8 @@ func Aborted(reason, format string, a ...interface{}) error {
} }
} }
// IsAborted determines if err is an error which indicates an aborted error.
// It supports wrapped errors.
func IsAborted(err error) bool { func IsAborted(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 10 return se.Code == 10
@ -189,6 +209,8 @@ func OutOfRange(reason, format string, a ...interface{}) error {
} }
} }
// IsOutOfRange determines if err is an error which indicates a out of range error.
// It supports wrapped errors.
func IsOutOfRange(err error) bool { func IsOutOfRange(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 11 return se.Code == 11
@ -206,6 +228,8 @@ func Unimplemented(reason, format string, a ...interface{}) error {
} }
} }
// IsUnimplemented determines if err is an error which indicates a unimplemented error.
// It supports wrapped errors.
func IsUnimplemented(err error) bool { func IsUnimplemented(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 12 return se.Code == 12
@ -226,6 +250,8 @@ func Internal(reason, format string, a ...interface{}) error {
} }
} }
// IsInternal determines if err is an error which indicates an internal server error.
// It supports wrapped errors.
func IsInternal(err error) bool { func IsInternal(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 13 return se.Code == 13
@ -243,6 +269,8 @@ func Unavailable(reason, format string, a ...interface{}) error {
} }
} }
// IsUnavailable determines if err is an error which indicates a unavailable error.
// It supports wrapped errors.
func IsUnavailable(err error) bool { func IsUnavailable(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 14 return se.Code == 14
@ -260,6 +288,8 @@ func DataLoss(reason, format string, a ...interface{}) error {
} }
} }
// IsDataLoss determines if err is an error which indicates a data loss error.
// It supports wrapped errors.
func IsDataLoss(err error) bool { func IsDataLoss(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 15 return se.Code == 15
@ -277,6 +307,8 @@ func Unauthorized(reason, format string, a ...interface{}) error {
} }
} }
// IsUnauthorized determines if err is an error which indicates a unauthorized error.
// It supports wrapped errors.
func IsUnauthorized(err error) bool { func IsUnauthorized(err error) bool {
if se := new(StatusError); errors.As(err, &se) { if se := new(StatusError); errors.As(err, &se) {
return se.Code == 16 return se.Code == 16

@ -1,7 +1,6 @@
package host package host
import ( import (
"fmt"
"net" "net"
"strconv" "strconv"
) )
@ -46,7 +45,7 @@ func Extract(hostport string, lis net.Listener) (string, error) {
} }
ifaces, err := net.Interfaces() ifaces, err := net.Interfaces()
if err != nil { if err != nil {
return "", fmt.Errorf("Failed to get net interfaces: %v", err) return "", err
} }
for _, iface := range ifaces { for _, iface := range ifaces {
addrs, err := iface.Addrs() addrs, err := iface.Addrs()

@ -4,8 +4,6 @@ import (
"fmt" "fmt"
) )
var nop Logger = new(nopLogger)
// Helper is a logger helper. // Helper is a logger helper.
type Helper struct { type Helper struct {
debug Logger debug Logger

@ -1,5 +0,0 @@
package log
type nopLogger struct{}
func (l *nopLogger) Print(kvpair ...interface{}) {}

@ -5,6 +5,8 @@ import (
"github.com/go-kratos/kratos/v2/errors" "github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/middleware" "github.com/go-kratos/kratos/v2/middleware"
//lint:ignore SA1019 grpc
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes" "github.com/golang/protobuf/ptypes"
"google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/genproto/googleapis/rpc/errdetails"
@ -71,7 +73,7 @@ func errorEncode(err error) error {
se, ok := errors.FromError(err) se, ok := errors.FromError(err)
if !ok { if !ok {
se = &errors.StatusError{ se = &errors.StatusError{
Code: 2, Code: 2,
Message: err.Error(), Message: err.Error(),
} }
} }

@ -10,8 +10,8 @@ type Registrar interface {
Deregister(ctx context.Context, service *ServiceInstance) error Deregister(ctx context.Context, service *ServiceInstance) error
} }
// Discoverer is service discovery. // Instancer is service instancer.
type Discoverer interface { type Instancer interface {
// Service return the service instances in memory according to the service name. // Service return the service instances in memory according to the service name.
Fetch(ctx context.Context, serviceName string) ([]*ServiceInstance, error) Fetch(ctx context.Context, serviceName string) ([]*ServiceInstance, error)
// Watch creates a watcher according to the service name. // Watch creates a watcher according to the service name.

@ -39,9 +39,9 @@ func WithMiddleware(m middleware.Middleware) ClientOption {
} }
// WithRegistry with client registry. // WithRegistry with client registry.
func WithRegistry(d registry.Discoverer) ClientOption { func WithRegistry(in registry.Instancer) ClientOption {
return func(o *clientOptions) { return func(o *clientOptions) {
o.discoverer = d o.instancer = in
} }
} }
@ -57,7 +57,7 @@ type clientOptions struct {
endpoint string endpoint string
timeout time.Duration timeout time.Duration
middleware middleware.Middleware middleware middleware.Middleware
discoverer registry.Discoverer instancer registry.Instancer
grpcOpts []grpc.DialOption grpcOpts []grpc.DialOption
} }
@ -83,11 +83,10 @@ func dial(ctx context.Context, insecure bool, opts ...ClientOption) (*grpc.Clien
o(&options) o(&options)
} }
var grpcOpts = []grpc.DialOption{ var grpcOpts = []grpc.DialOption{
grpc.WithTimeout(options.timeout), grpc.WithUnaryInterceptor(unaryClientInterceptor(options.middleware, options.timeout)),
grpc.WithUnaryInterceptor(UnaryClientInterceptor(options.middleware)),
} }
if options.discoverer != nil { if options.instancer != nil {
grpcOpts = append(grpcOpts, grpc.WithResolvers(discovery.NewBuilder(options.discoverer))) grpcOpts = append(grpcOpts, grpc.WithResolvers(discovery.NewBuilder(options.instancer)))
} }
if insecure { if insecure {
grpcOpts = append(grpcOpts, grpc.WithInsecure()) grpcOpts = append(grpcOpts, grpc.WithInsecure())
@ -98,11 +97,15 @@ func dial(ctx context.Context, insecure bool, opts ...ClientOption) (*grpc.Clien
return grpc.DialContext(ctx, options.endpoint, grpcOpts...) return grpc.DialContext(ctx, options.endpoint, grpcOpts...)
} }
// UnaryClientInterceptor retruns a unary client interceptor. func unaryClientInterceptor(m middleware.Middleware, timeout time.Duration) grpc.UnaryClientInterceptor {
func UnaryClientInterceptor(m middleware.Middleware) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
ctx = transport.NewContext(ctx, transport.Transport{Kind: transport.KindGRPC}) ctx = transport.NewContext(ctx, transport.Transport{Kind: transport.KindGRPC})
ctx = NewClientContext(ctx, ClientInfo{FullMethod: method}) ctx = NewClientContext(ctx, ClientInfo{FullMethod: method})
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
h := func(ctx context.Context, req interface{}) (interface{}, error) { h := func(ctx context.Context, req interface{}) (interface{}, error) {
return reply, invoker(ctx, method, req, reply, cc, opts...) return reply, invoker(ctx, method, req, reply, cc, opts...)
} }

@ -33,11 +33,11 @@ type clientKey struct{}
// NewClientContext returns a new Context that carries value. // NewClientContext returns a new Context that carries value.
func NewClientContext(ctx context.Context, info ClientInfo) context.Context { func NewClientContext(ctx context.Context, info ClientInfo) context.Context {
return context.WithValue(ctx, serverKey{}, info) return context.WithValue(ctx, clientKey{}, info)
} }
// FromClientContext returns the Transport value stored in ctx, if any. // FromClientContext returns the Transport value stored in ctx, if any.
func FromClientContext(ctx context.Context) (info ClientInfo, ok bool) { func FromClientContext(ctx context.Context) (info ClientInfo, ok bool) {
info, ok = ctx.Value(serverKey{}).(ClientInfo) info, ok = ctx.Value(clientKey{}).(ClientInfo)
return return
} }

@ -21,15 +21,15 @@ func WithLogger(logger log.Logger) Option {
} }
type builder struct { type builder struct {
discoverer registry.Discoverer instancer registry.Instancer
logger log.Logger logger log.Logger
} }
// NewBuilder creates a builder which is used to factory registry resolvers. // NewBuilder creates a builder which is used to factory registry resolvers.
func NewBuilder(r registry.Discoverer, opts ...Option) resolver.Builder { func NewBuilder(in registry.Instancer, opts ...Option) resolver.Builder {
b := &builder{ b := &builder{
discoverer: r, instancer: in,
logger: log.DefaultLogger, logger: log.DefaultLogger,
} }
for _, o := range opts { for _, o := range opts {
o(b) o(b)
@ -38,7 +38,7 @@ func NewBuilder(r registry.Discoverer, opts ...Option) resolver.Builder {
} }
func (d *builder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { func (d *builder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
w, err := d.discoverer.Watch(context.Background(), target.Endpoint) w, err := d.instancer.Watch(context.Background(), target.Endpoint)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -94,8 +94,7 @@ func NewServer(opts ...ServerOption) *Server {
} }
var grpcOpts = []grpc.ServerOption{ var grpcOpts = []grpc.ServerOption{
grpc.ChainUnaryInterceptor( grpc.ChainUnaryInterceptor(
UnaryServerInterceptor(srv.middleware), unaryServerInterceptor(srv.middleware, srv.timeout),
UnaryTimeoutInterceptor(srv.timeout),
), ),
} }
if len(srv.grpcOpts) > 0 { if len(srv.grpcOpts) > 0 {
@ -134,20 +133,15 @@ func (s *Server) Stop() error {
return nil return nil
} }
// UnaryTimeoutInterceptor returns a unary timeout interceptor. func unaryServerInterceptor(m middleware.Middleware, timeout time.Duration) grpc.UnaryServerInterceptor {
func UnaryTimeoutInterceptor(timeout time.Duration) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return handler(ctx, req)
}
}
// UnaryServerInterceptor returns a unary server interceptor.
func UnaryServerInterceptor(m middleware.Middleware) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ctx = transport.NewContext(ctx, transport.Transport{Kind: transport.KindGRPC}) ctx = transport.NewContext(ctx, transport.Transport{Kind: transport.KindGRPC})
ctx = NewServerContext(ctx, ServerInfo{Server: info.Server, FullMethod: info.FullMethod}) ctx = NewServerContext(ctx, ServerInfo{Server: info.Server, FullMethod: info.FullMethod})
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
h := func(ctx context.Context, req interface{}) (interface{}, error) { h := func(ctx context.Context, req interface{}) (interface{}, error) {
return handler(ctx, req) return handler(ctx, req)
} }

Loading…
Cancel
Save