2

I have a getter context : HTTP::Server::Context and a login form.
Now I want to parse data from context.request.body to get username and password which user input.

The response's content type: application/x-www-form-urlencoded

1 Answers1

4

HTTP::Params.parse is what you're looking for:

# Based on the sample code in https://crystal-lang.org/ home
require "http/server"

server = HTTP::Server.new(8080) do |context|
  context.response.content_type = "text/plain"
  if body = context.request.body
    params = HTTP::Params.parse(body)
    context.response.print "Hello #{params["user"]? || "Anonymous"}!"
  else
    context.response.print "You didn't POST any data :("
  end
end

puts "Listening on http://127.0.0.1:8080"
server.listen
mgarciaisaia
  • 14,521
  • 8
  • 57
  • 81
  • Thank you so much. –  Dec 02 '16 at 23:03
  • 1
    Actually I using crouter for routing, but I try to use HTTP::Params to parse request.body and it generates error: no overload matches 'HTTP::Params.parse' with type. But my mistake is crouter has already a params variable, to get body data, just use params["user"] like you did, don't need to parse data again. –  Dec 02 '16 at 23:06
  • Yeah - one would expect parsing those options is one of the things a framework would do for you. This is the "hands-on" approach - your framework would probably be calling this function. Glad it helped, anyways :) – mgarciaisaia Dec 04 '16 at 04:15
  • Thanks mgarciaisaia, wish you a nice weekend :) –  Dec 04 '16 at 12:00