github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/requests/resolver/resolver.go (about)

     1  /*
     2   * Copyright (C) 2020 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package resolver
    19  
    20  import (
    21  	"context"
    22  	"net"
    23  )
    24  
    25  // ResolveContext specifies the resolve function for doing custom DNS lookup.
    26  type ResolveContext func(ctx context.Context, network, addr string) (addrs []string, err error)
    27  
    28  // NewResolverMap creates resolver with predefined host -> IP map.
    29  func NewResolverMap(hostToIP map[string][]string) ResolveContext {
    30  	return func(ctx context.Context, network, addr string) ([]string, error) {
    31  		addrHost, addrPort, err := net.SplitHostPort(addr)
    32  		if err != nil {
    33  			return nil, &net.DNSError{Err: "invalid dial address", Name: addr, Server: "localmap", IsNotFound: true}
    34  		}
    35  
    36  		addrs := []string{addr}
    37  
    38  		for _, addrIP := range FetchDNSFromCache(addrHost) {
    39  			addrs = append(addrs, net.JoinHostPort(addrIP, addrPort))
    40  		}
    41  
    42  		for _, addrIP := range hostToIP[addrHost] {
    43  			addrs = append(addrs, net.JoinHostPort(addrIP, addrPort))
    44  		}
    45  
    46  		return deduplicate(addrs), nil
    47  	}
    48  }
    49  
    50  func deduplicate(list []string) (result []string) {
    51  	m := make(map[string]struct{})
    52  
    53  	for _, v := range list {
    54  		if _, ok := m[v]; !ok {
    55  			result = append(result, v)
    56  			m[v] = struct{}{}
    57  		}
    58  	}
    59  
    60  	return result
    61  }