Browse Source

[h2o.cr] add /json end point (#4075)

* [h2o.cr] add /json end point

* [h2o.cr] fix obvious readme title
YOU 6 years ago
parent
commit
fc76825ae3

+ 2 - 2
frameworks/Crystal/h2o.cr/README.md

@@ -2,6 +2,6 @@
 
 
 Crystal bindings to h2o
 Crystal bindings to h2o
 
 
-### Plaintext
+### notes
 
 
-h2o.cr currently only support plaintext requests
+h2o.cr currently only support plaintext and json requests

+ 1 - 0
frameworks/Crystal/h2o.cr/benchmark_config.json

@@ -3,6 +3,7 @@
   "tests": [
   "tests": [
     {
     {
       "default": {
       "default": {
+        "json_url": "/json",
         "plaintext_url": "/hello",
         "plaintext_url": "/hello",
         "port": 7890,
         "port": 7890,
         "approach": "Realistic",
         "approach": "Realistic",

+ 24 - 2
frameworks/Crystal/h2o.cr/h2o_evloop_hello.cr

@@ -1,5 +1,6 @@
 require "reset/prelude"
 require "reset/prelude"
 require "reset/patches"
 require "reset/patches"
+require "reset/json"
 require "h2o/h2o_evloop"
 require "h2o/h2o_evloop"
 
 
 class H2oHello < H2o
 class H2oHello < H2o
@@ -24,6 +25,26 @@ class H2oHello < H2o
     end
     end
   end
   end
 
 
+  macro json
+    Handler.new do |handler, req|
+      generator = uninitialized LibH2o::H2oGeneratorT[2]
+      alloc = uninitialized UInt8[32]
+      buf = StackBuffer.new(alloc.to_unsafe)
+
+      len = {message: "Hello, World!"}.to_json(buf)
+      body = LibH2o::H2oIovecT.new(base: buf, len: len)
+
+      req.value.res.status = 200
+      req.value.res.reason = "OK"
+      req.value.res.content_length = body.len
+
+      h2o_add_header(req, H2O_TOKEN_CONTENT_TYPE, "application/json")
+      h2o_start_response(req, generator)
+      h2o_send(req, pointerof(body), 1, LibH2o::H2oSendState::H2OSendStateFinal)
+      0
+    end
+  end
+
   def on_accept(listener : LibH2o::H2oSocketT*, err : LibC::Char*) : Void
   def on_accept(listener : LibH2o::H2oSocketT*, err : LibC::Char*) : Void
     return if err
     return if err
     return unless s = h2o_evloop_socket_accept(listener)
     return unless s = h2o_evloop_socket_accept(listener)
@@ -71,8 +92,11 @@ class H2oHello < H2o
 
 
   def run : Void
   def run : Void
     h2o_config_init(pointerof(@config))
     h2o_config_init(pointerof(@config))
+    @config.server_name = h2o_iovec_init("h2o")
+
     hostconf = h2o_config_register_host(pointerof(@config), h2o_iovec_init("default"), 65535)
     hostconf = h2o_config_register_host(pointerof(@config), h2o_iovec_init("default"), 65535)
     register_handler(hostconf, "/hello", hello)
     register_handler(hostconf, "/hello", hello)
+    register_handler(hostconf, "/json", json)
 
 
     h2o_context_init(pointerof(@ctx), @loop, pointerof(@config))
     h2o_context_init(pointerof(@ctx), @loop, pointerof(@config))
 
 
@@ -88,5 +112,3 @@ class H2oHello < H2o
 end
 end
 
 
 H2oHello.run
 H2oHello.run
-
-