require 'socksify/http'

module Faraday
  class Adapter
    register_middleware net_http_socks_compat: :NetHttpSocksCompat

    class NetHttpSocksCompat < NetHttp
      # Modification of the :net_http adapter to support socks5 proxies.
      #
      # If the proxy setting of the Faraday::Connection object is set to:
      #
      # socks5://127.0.0.1:1080
      #
      # This will use that socks5 for all outbound requests.

      def net_http_connection(env)
        proxy = env[:request][:proxy]
        if !proxy.nil? && proxy[:uri].scheme == 'socks5'
          return Net::HTTP::SOCKSProxy(
            proxy[:uri].host,
            proxy[:uri].port
          ).new(env[:url].host, env[:url].port)
        end

        super(env)
      end
    end
  end
end
