Files
cpp-httplib/docs/code-cleanup.md
2026-01-12 21:03:12 -05:00

76 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# TLS抽象化API導入後のコード整理・簡潔化ガイド
---
## 1. 共通インターフェースの徹底利用
- `tls_ctx_t`, `tls_session_t`, `tls_cert_t` などの抽象型を積極的に使い、API呼び出し部分でのみバックエンド分岐する。
- 例:
```cpp
// 共通API
bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert, const char *key, const char *password);
// バックエンドごとの実装は .cc で分岐
```
## 2. 条件付きコンパイルの整理
- `#ifdef CPPHTTPLIB_OPENSSL_SUPPORT` や `#ifdef CPPHTTPLIB_MBEDTLS_SUPPORT` の分岐は、実装部(.ccに集約し、ヘッダでは極力抽象APIのみ宣言。
- 共通部分は `#ifdef` を減らし、実装のみに限定。
## 3. 重複コードの関数化
- 例えば、証明書のロードやエラー処理など、OpenSSL/MbedTLSで似た処理は共通関数にまとめる。
- 例:
```cpp
bool tls_load_ca(tls_ctx_t ctx, const std::string &file, const std::string &dir);
```
## 4. 共通エラーハンドリング
- `TlsError` 構造体や `ErrorCode` enum を全バックエンドで統一利用。
- エラー文字列変換も共通APIでラップ。
## 5. クライアント・サーバの共通化
- `SSLClient`/`SSLServer` のコンストラクタや証明書更新処理は、内部で `tls_*` APIを呼ぶだけにし、分岐を減らす。
## 6. 冗長なパラメータ・状態管理の削減
- 例えば `ctx_` や `session_` の型は `void*` で統一し、型キャストは実装部でのみ行う。
- `host_components_` の分割処理なども共通関数化。
## 7. コメント・ドキュメントの整理
- バックエンドごとの注意点は実装部にコメントを集約し、ヘッダはAPI仕様のみに集中。
---
### 例: 冗長な証明書ロード処理の統一
```cpp
// filepath: /Users/yuji/Projects/cpp-httplib-ssl/httplib.h
// ...existing code...
namespace detail {
namespace tls {
// 共通API
inline bool tls_load_ca(tls_ctx_t ctx, const std::string &file, const std::string &dir) {
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
if (!file.empty()) return tls_load_ca_file(ctx, file.c_str());
if (!dir.empty()) return tls_load_ca_dir(ctx, dir.c_str());
#elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
if (!file.empty()) return tls_load_ca_file(ctx, file.c_str());
if (!dir.empty()) return tls_load_ca_dir(ctx, dir.c_str());
#endif
return false;
}
} // namespace tls
} // namespace detail
// ...existing code...
```
---
## まとめ
- 抽象APIの利用と実装部での分岐を徹底し、ヘッダはシンプルに。
- 重複処理は関数化し、条件付きコンパイルは最小限に。
- 安全性・正確性・パフォーマンスは維持しつつ、可読性・保守性を向上。
---
ご要望に応じて、具体的なリファクタリング案やコード修正例をさらにご提案できます。どの部分を優先的に整理したいかご指定ください。