github.com/searKing/golang/go@v1.2.117/net/resolver/unix/unix.go (about)

     1  // Copyright 2021 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package unix implements a resolver for unix targets.
     6  package unix
     7  
     8  import (
     9  	"context"
    10  	"fmt"
    11  
    12  	rand_ "github.com/searKing/golang/go/math/rand"
    13  	"github.com/searKing/golang/go/net/resolver"
    14  )
    15  
    16  const unixScheme = "unix"
    17  const unixAbstractScheme = "unix-abstract"
    18  
    19  type builder struct {
    20  	scheme string
    21  }
    22  
    23  func (b *builder) Build(ctx context.Context, target resolver.Target, opts ...resolver.BuildOption) (resolver.Resolver, error) {
    24  	var opt resolver.Build
    25  	opt.ApplyOptions(opts...)
    26  	cc := opt.ClientConn
    27  	if target.Authority != "" {
    28  		return nil, fmt.Errorf("invalid (non-empty) authority: %v", target.Authority)
    29  	}
    30  	addr := target.Endpoint
    31  	if b.scheme == unixAbstractScheme {
    32  		// prepend "\x00" to address for unix-abstract
    33  		addr = "\x00" + addr
    34  	}
    35  
    36  	if cc != nil {
    37  		_ = cc.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: addr}}})
    38  	}
    39  	return &nopResolver{Addresses: []resolver.Address{{Addr: addr}}}, nil
    40  }
    41  
    42  func (b *builder) Scheme() string {
    43  	return b.scheme
    44  }
    45  
    46  type nopResolver struct {
    47  	// Addresses is the latest set of resolved addresses for the target.
    48  	Addresses []resolver.Address
    49  }
    50  
    51  func (r *nopResolver) ResolveOneAddr(ctx context.Context, opts ...resolver.ResolveOneAddrOption) (resolver.Address, error) {
    52  	if len(r.Addresses) == 0 {
    53  		return resolver.Address{}, fmt.Errorf("resolve target, but no addr")
    54  	}
    55  	return r.Addresses[rand_.Intn(len(r.Addresses))], nil
    56  }
    57  
    58  func (r *nopResolver) ResolveAddr(ctx context.Context, opts ...resolver.ResolveAddrOption) ([]resolver.Address, error) {
    59  	return r.Addresses, nil
    60  }
    61  
    62  func (*nopResolver) ResolveNow(ctx context.Context, opts ...resolver.ResolveNowOption) {}
    63  
    64  func (*nopResolver) Close() {}
    65  
    66  func init() {
    67  	resolver.Register(&builder{scheme: unixScheme})
    68  	resolver.Register(&builder{scheme: unixAbstractScheme})
    69  }