Skip to content

Instantly share code, notes, and snippets.

@cpq
Last active June 6, 2025 18:32
Show Gist options
  • Save cpq/806be4d3be1328af0b8c84cc9646b081 to your computer and use it in GitHub Desktop.
Save cpq/806be4d3be1328af0b8c84cc9646b081 to your computer and use it in GitHub Desktop.
How to send a JSON REST API response with a list of options
size_t print_entries(void (*out)(char, void *), void *ptr, va_list *ap) {
const char **names = va_arg(*ap, const char **);
size_t i, len = 0;
for (i = 0; names[i] != NULL; i++) {
len += mg_xprintf(out, ptr, "%s%m",
i > 0 ? "," : "", // Comma-separate entries
MG_ESC(names[i])); // JSON-escape string
}
return len;
}
void my_reply_entries(struct mg_connection *c, struct mg_http_message *hm) {
const char *headers =
"Cache-Control: no-cache\r\n"
"Content-Type: application/json\r\n";
const char *names[] = {"aa", "bb", "cc", NULL};
(void) hm;
mg_http_reply(c, 200, headers, "[%M]\n", print_entries, names);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment