code wiki / _hdl_build / nx_apistack_problem.nx
nx_apistack_problem.nx source
↩ module page · 38 lines · 1799 B
1// nx_apistack_problem.nx -- CAP-API-PROBLEM: RFC 7807 / RFC 9457 error contract (application/problem+json) for /api.
2// Replaces ad-hoc {"error":..} with a stable machine-readable shape {type,title,status,detail} + stable type URIs, so
3// clients can branch on `type` deterministically. Pure serializer (byte-reproducible), JSON-escaped. license_tier: ORIGINAL
4import "nx_syscalls.nx"
5
6func pr_cat(buf: *u8, off: i64, s: *u8) -> i64 { var i: i64=0; while s[i]!=(0 as u8){buf[off+i]=s[i];i=i+1} return off+i }
7func pr_catn(buf: *u8, off: i64, v: i64) -> i64 {
8 var t: i64=v; if t<0{buf[off]=45 as u8;off=off+1;t=0-t}
9 let tm:*u8=sys_mmap(24); var k:i64=0; if t==0{tm[0]=48 as u8;k=1}
10 while t>0{tm[k]=(48+(t%10)) as u8;t=t/10;k=k+1}
11 var j:i64=0; while j<k{buf[off+j]=tm[k-1-j];j=j+1}
12 return off+k
13}
14// append a JSON-escaped string value (escapes " and \).
15func pr_cat_esc(buf: *u8, off: i64, s: *u8) -> i64 {
16 var o: i64 = off; var i: i64 = 0
17 while s[i] != (0 as u8) {
18 let c: i64 = (s[i] as i64) & 0xff
19 if c == 34 { buf[o]=92 as u8; o=o+1; buf[o]=34 as u8; o=o+1 }
20 else { if c == 92 { buf[o]=92 as u8; o=o+1; buf[o]=92 as u8; o=o+1 }
21 else { buf[o]=c as u8; o=o+1 } }
22 i = i + 1
23 }
24 return o
25}
26// build the RFC7807 problem+json body. Returns length.
27func pr_build_json(out: *u8, type_uri: *u8, title: *u8, status: i64, detail: *u8) -> i64 {
28 var o: i64 = pr_cat(out, 0, "{\"type\":\"" as *u8)
29 o = pr_cat_esc(out, o, type_uri)
30 o = pr_cat(out, o, "\",\"title\":\"" as *u8)
31 o = pr_cat_esc(out, o, title)
32 o = pr_cat(out, o, "\",\"status\":" as *u8)
33 o = pr_catn(out, o, status)
34 o = pr_cat(out, o, ",\"detail\":\"" as *u8)
35 o = pr_cat_esc(out, o, detail)
36 o = pr_cat(out, o, "\"}" as *u8)
37 return o
38}