vif/examples/05-json/main.ml

60 lines
1.4 KiB
OCaml
Raw Normal View History

2025-02-01 15:54:10 +00:00
#require "vif" ;;
type foo =
2025-02-02 12:29:07 +00:00
{ username: string
; password: string
; age: int option
; address: string option }
2025-02-01 15:54:10 +00:00
;;
let foo =
let open Json_encoding in
let username = req "username" string in
let password = req "password" string in
let age = opt "age" int in
let address = opt "address" string in
let foo = obj4 username password age address in
2025-02-02 12:29:07 +00:00
let prj { username; password; age; address } =
(username, password, age, address)
in
let inj (username, password, age, address) =
{ username; password; age; address }
in
2025-02-01 15:54:10 +00:00
conv prj inj foo
;;
2025-02-13 16:17:00 +00:00
open Vif ;;
let deserialize req _server () =
2025-02-08 15:37:56 +00:00
match Vif.Request.of_json req with
2025-02-01 15:54:10 +00:00
| Ok (foo : foo) ->
2025-02-02 12:29:07 +00:00
let str =
Fmt.str "username: %s, password: %s, age: %a, address: %a\n"
foo.username foo.password
Fmt.(Dump.option int)
foo.age
Fmt.(Dump.option string)
foo.address
in
2025-02-13 16:17:00 +00:00
let* () = Response.with_string req str in
Response.respond `OK
| Error (`Msg msg) ->
let* () = Response.with_string req msg in
Response.respond (`Code 422)
2025-02-02 12:29:07 +00:00
;;
2025-02-01 15:54:10 +00:00
let routes =
let open Vif.U in
let open Vif.R in
let open Vif.Content_type in
[ post (json_encoding foo) (rel /?? nil) --> deserialize ]
;;
2025-02-13 16:17:00 +00:00
let default req target _server () =
2025-02-01 15:54:10 +00:00
let str = Fmt.str "%s not found\n" target in
2025-02-13 16:17:00 +00:00
let* () = Response.with_string req str in
Response.respond `Not_found
2025-02-01 15:54:10 +00:00
;;
2025-02-02 12:29:07 +00:00
let () = Miou_unix.run @@ fun () -> Vif.run ~default routes () ;;