Skip to content

Commit

Permalink
FEAT: simple Web API example
Browse files Browse the repository at this point in the history
  • Loading branch information
Oldes committed Jun 1, 2023
1 parent 6364e08 commit 34aeb4b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
3 changes: 3 additions & 0 deletions client-test.r3
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ foreach test [
[ assert-http 200 http://localhost:8081/humans.txt ]
[ assert-http/post 200 http://localhost:8081 {msg=hello} ]
[ assert-http/post 200 http://localhost:8081 [post [user-agent: "UA"] "hello"] ]
[ assert-http/post 200 http://localhost:8081/api/v2/do #(token: "SOME_SECRET" code: "[1 + 1]") ]
[ assert-http/post 401 http://localhost:8081/api/v2/do #(token: "ELSE_SECRET" code: "[1 + 1]") ]
[ assert-http/post 200 http://localhost:8081/api/v2/do {token=SOME_SECRET&code=1%20%2B%202} ]

][
print-horizontal-line
Expand Down
28 changes: 27 additions & 1 deletion server-test.r3
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,33 @@ http-server/config/actor 8081 [
]
]
]
On-Post-Received: func [ctx [object!]][
On-Post-Received: func [ctx [object!] /local data][
if ctx/inp/target/file = %/api/v2/do [
;- A primitive API example
try/except [
;?? ctx/inp
data: ctx/inp/content
unless map? data [data: to map! ctx/inp/content/1] ;;= url-encoded input
;; using plain secret in this example,
;; but it should be replaced with something better in the real life
if data/token <> "SOME_SECRET" [
ctx/out/status: 401 ;= Unauthorized
exit
]
;; reusing the input for an output
;; without the token...
remove/key data 'token
;; but with result of the input expression...
;@@ NOTE that there is no security setting, so the code may be dangerous!
data/result: mold/all try load data/code
ctx/out/header/Content-Type: "application/json"
ctx/out/content: to-json data
][
ctx/out/status: 400 ;= Bad request
]
exit
]
;; else just return what we received...
ctx/out/content: ajoin [
"<br/>Request header:<pre>" mold ctx/inp/header </pre>
"Received <code>" ctx/inp/header/Content-Type/1
Expand Down

0 comments on commit 34aeb4b

Please sign in to comment.