| 52 | } |
| 53 | |
| 54 | bool server_http_context::init(const common_params & params) { |
| 55 | path_prefix = params.api_prefix; |
| 56 | port = params.port; |
| 57 | hostname = params.hostname; |
| 58 | |
| 59 | auto & srv = pimpl->srv; |
| 60 | |
| 61 | #ifdef CPPHTTPLIB_OPENSSL_SUPPORT |
| 62 | if (params.ssl_file_key != "" && params.ssl_file_cert != "") { |
| 63 | LOG_INF("Running with SSL: key = %s, cert = %s\n", params.ssl_file_key.c_str(), params.ssl_file_cert.c_str()); |
| 64 | srv.reset( |
| 65 | new httplib::SSLServer(params.ssl_file_cert.c_str(), params.ssl_file_key.c_str()) |
| 66 | ); |
| 67 | } else { |
| 68 | LOG_INF("Running without SSL\n"); |
| 69 | srv.reset(new httplib::Server()); |
| 70 | } |
| 71 | #else |
| 72 | if (params.ssl_file_key != "" && params.ssl_file_cert != "") { |
| 73 | LOG_ERR("Server is built without SSL support\n"); |
| 74 | return false; |
| 75 | } |
| 76 | srv.reset(new httplib::Server()); |
| 77 | #endif |
| 78 | |
| 79 | srv->set_default_headers({{"Server", "llama.cpp"}}); |
| 80 | srv->set_logger(log_server_request); |
| 81 | srv->set_exception_handler([](const httplib::Request &, httplib::Response & res, const std::exception_ptr & ep) { |
| 82 | // this is fail-safe; exceptions should already handled by `ex_wrapper` |
| 83 | |
| 84 | std::string message; |
| 85 | try { |
| 86 | std::rethrow_exception(ep); |
| 87 | } catch (const std::exception & e) { |
| 88 | message = e.what(); |
| 89 | } catch (...) { |
| 90 | message = "Unknown Exception"; |
| 91 | } |
| 92 | |
| 93 | res.status = 500; |
| 94 | res.set_content(message, "text/plain"); |
| 95 | LOG_ERR("got exception: %s\n", message.c_str()); |
| 96 | }); |
| 97 | |
| 98 | srv->set_error_handler([](const httplib::Request &, httplib::Response & res) { |
| 99 | if (res.status == 404) { |
| 100 | res.set_content( |
| 101 | safe_json_to_str(json { |
| 102 | {"error", { |
| 103 | {"message", "File Not Found"}, |
| 104 | {"type", "not_found_error"}, |
| 105 | {"code", 404} |
| 106 | }} |
| 107 | }), |
| 108 | "application/json; charset=utf-8" |
| 109 | ); |
| 110 | } |
| 111 | // for other error codes, we skip processing here because it's already done by res->error() |