let (module Bumpable) = int_bumper in Bumpable.bump 3;;
. Well, it seems that I've never seen this syntax before, is that some kind of pattern-matching?
Can we print the parameter in the terminal that run the opium ? I wrote a function to debug the request from the client
let getid = get "/getreq" (fun req ->
let uri = Request.uri req in
let ua = Uri.get_query_param uri "reqs" in
let resp =
match ua with
| Some cont -> cont
| None -> "-1"
in
Printf.printf "abc";
`String resp |> respond')
I can't see the "abc" in the terminal. What's more, if I change "abc" to resp
, there's an error
Error: This expression has type bytes but an expression was expected of type
('a, out_channel, unit) format =
('a, out_channel, unit, unit, unit, unit) format6
print_endline (Sexp.to_string_hum (Response.sexp_of_t resp))
thank you @rgrinberg
I'm reading the source code of opium, I found a lot of >>|
, for example:
module Request_helpers = struct
let json_exn req =
req |> Request.body |> Body.to_string >>| Ezjsonm.from_string
let string_exn req =
req |> Request.body |> Body.to_string
let pairs_exn req =
req |> Request.body |> Body.to_string >>| Uri.query_of_encoded
end
When I was reading RWO, it saids >>|
is Deferred.map
, is that the same in opium?
Async.Std
brings >>|
into scope
I combined the examples of both get
and post
parameters as
let getid req =
let uri = Request.uri req in
let ua = Uri.get_query_param uri "ua" in
let resp =
match ua with
| Some cont -> cont
| None -> "na"
in
App.string_of_body_exn req >>| fun rbody ->
print_endline (rbody^resp);
respond (`String (rbody^resp))
I was wondering if it was the most elegant way?
resp
as: let resp = Option.value (Uri.get_query_param uri “ua”) ~default:”na” in…
respond
works well for me, my testing code was:let getid req =
let uri = Request.uri req in
let resp = Option.value (Uri.get_query_param uri "ua") ~default:"na"
in App.string_of_body_exn req >>| fun rbody ->
print_endline (rbody^resp);
respond (`String (rbody^resp))
let _ =
App.empty
|> get "/" hello
|> post "/gid" getid
|> App.run_command
open Core_kernel.Std
open Opium.Std
type person = {
name: string;
age: int;
}
let json_of_person { name ; age } =
let open Ezjsonm in
dict [ "name", (string name)
; "age", (int age) ]
let print_param = put "/hello/:name" begin fun req ->
`String ("Hello " ^ param req "name") |> respond'
end
let print_person = get "/person/:name/:age" begin fun req ->
let person = {
name = param req "name";
age = "age" |> param req |> Int.of_string;
} in
`Json (person |> json_of_person |> Ezjsonm.wrap) |> respond'
end
let _ =
App.empty
|> print_param
|> print_person
|> App.run_command
$ curl -X PUT http://localhost:9000/hello/testing
cookie
, I found an example to get the cookie from a req as https://github.com/rgrinberg/opium/blob/119a39c6c6fe937bf44eee9c548711bbbcf6e452/examples/sample.ml#L31 , I was wondering if maybe we could get some other header such as referer
?