75: def self.env_for(uri="", opts={})
76: uri = URI(uri)
77: uri.path = "/#{uri.path}" unless uri.path[0] == ?/
78:
79: env = DEFAULT_ENV.dup
80:
81: env["REQUEST_METHOD"] = opts[:method] ? opts[:method].to_s.upcase : "GET"
82: env["SERVER_NAME"] = uri.host || "example.org"
83: env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80"
84: env["QUERY_STRING"] = uri.query.to_s
85: env["PATH_INFO"] = (!uri.path || uri.path.empty?) ? "/" : uri.path
86: env["rack.url_scheme"] = uri.scheme || "http"
87: env["HTTPS"] = env["rack.url_scheme"] == "https" ? "on" : "off"
88:
89: env["SCRIPT_NAME"] = opts[:script_name] || ""
90:
91: if opts[:fatal]
92: env["rack.errors"] = FatalWarner.new
93: else
94: env["rack.errors"] = StringIO.new
95: end
96:
97: if params = opts[:params]
98: if env["REQUEST_METHOD"] == "GET"
99: params = Utils.parse_nested_query(params) if params.is_a?(String)
100: params.update(Utils.parse_nested_query(env["QUERY_STRING"]))
101: env["QUERY_STRING"] = Utils.build_nested_query(params)
102: elsif !opts.has_key?(:input)
103: opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
104: if params.is_a?(Hash)
105: if data = Utils::Multipart.build_multipart(params)
106: opts[:input] = data
107: opts["CONTENT_LENGTH"] ||= data.length.to_s
108: opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Utils::Multipart::MULTIPART_BOUNDARY}"
109: else
110: opts[:input] = Utils.build_nested_query(params)
111: end
112: else
113: opts[:input] = params
114: end
115: end
116: end
117:
118: empty_str = ""
119: empty_str.force_encoding("ASCII-8BIT") if empty_str.respond_to? :force_encoding
120: opts[:input] ||= empty_str
121: if String === opts[:input]
122: rack_input = StringIO.new(opts[:input])
123: else
124: rack_input = opts[:input]
125: end
126:
127: rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding)
128: env['rack.input'] = rack_input
129:
130: env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s
131:
132: opts.each { |field, value|
133: env[field] = value if String === field
134: }
135:
136: env
137: end