Created
January 28, 2026 10:10
-
-
Save cpq/e30b87de67bd2a320cae47a546561892 to your computer and use it in GitHub Desktop.
HTTPS redirector for Mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| static const char *s_http_addr = "https://0.0.0.0:8000"; | |
| static const char *s_https_addr = "https://0.0.0.0:8443"; | |
| // Self signed certificates, see | |
| // https://github.com/cesanta/mongoose/blob/master/test/certs/generate.sh | |
| static const char *s_tls_cert = | |
| "-----BEGIN CERTIFICATE-----\n" | |
| "MIIBMTCB2aADAgECAgkAluqkgeuV/zUwCgYIKoZIzj0EAwIwEzERMA8GA1UEAwwI\n" | |
| "TW9uZ29vc2UwHhcNMjQwNTA3MTQzNzM2WhcNMzQwNTA1MTQzNzM2WjARMQ8wDQYD\n" | |
| "VQQDDAZzZXJ2ZXIwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASo3oEiG+BuTt5y\n" | |
| "ZRyfwNr0C+SP+4M0RG2pYkb2v+ivbpfi72NHkmXiF/kbHXtgmSrn/PeTqiA8M+mg\n" | |
| "BhYjDX+zoxgwFjAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwIDRwAw\n" | |
| "RAIgTXW9MITQSwzqbNTxUUdt9DcB+8pPUTbWZpiXcA26GMYCIBiYw+DSFMLHmkHF\n" | |
| "+5U3NXW3gVCLN9ntD5DAx8LTG8sB\n" | |
| "-----END CERTIFICATE-----\n"; | |
| static const char *s_tls_key = | |
| "-----BEGIN EC PRIVATE KEY-----\n" | |
| "MHcCAQEEIAVdo8UAScxG7jiuNY2UZESNX/KPH8qJ0u0gOMMsAzYWoAoGCCqGSM49\n" | |
| "AwEHoUQDQgAEqN6BIhvgbk7ecmUcn8Da9Avkj/uDNERtqWJG9r/or26X4u9jR5Jl\n" | |
| "4hf5Gx17YJkq5/z3k6ogPDPpoAYWIw1/sw==\n" | |
| "-----END EC PRIVATE KEY-----\n"; | |
| // HTTPS listener serves requests | |
| static void https_ev_handler(struct mg_connection *c, int ev, void *ev_data) { | |
| if (ev == MG_EV_ACCEPT && c->is_tls) { | |
| struct mg_tls_opts opts; | |
| memset(&opts, 0, sizeof(opts)); | |
| opts.cert = mg_str(s_tls_cert); | |
| opts.key = mg_str(s_tls_key); | |
| mg_tls_init(c, &opts); | |
| } | |
| if (ev == MG_EV_HTTP_MSG) { | |
| struct mg_http_message *hm = (struct mg_http_message *) ev_data; | |
| char buf[256]; | |
| mg_snprintf(buf, sizeof(buf), "Location: %s%.*s\r\n", s_http_addr, | |
| hm->uri.len, hm->uri.buf); | |
| mg_http_reply(c, 302, buf, "%s", buf); // 302 redirect | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment