MCPcopy Create free account
hub / github.com/ZToolsCenter/ZTools / handleRequest

Method handleRequest

src/main/core/httpServer.ts:125–167  ·  view source on GitHub ↗
(req: IncomingMessage, res: ServerResponse)

Source from the content-addressed store, hash-verified

123 }
124
125 private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
126 if (req.method === 'OPTIONS') {
127 res.writeHead(204, {
128 'Access-Control-Allow-Origin': '*',
129 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
130 'Access-Control-Allow-Headers': 'Content-Type, Authorization'
131 })
132 res.end()
133 return
134 }
135
136 const url = req.url || '/'
137
138 // GET / 无需认证,返回欢迎信息
139 if (req.method === 'GET' && url === '/') {
140 this.sendJson(res, 200, { code: 0, message: 'Hello ZTools' })
141 return
142 }
143
144 if (req.method !== 'POST') {
145 this.sendJson(res, 405, { code: 405, message: '仅支持 POST 请求' })
146 return
147 }
148
149 const authHeader = req.headers['authorization']
150 const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null
151 if (!token || token !== this.config.apiKey) {
152 this.sendJson(res, 401, { code: 401, message: 'API 密钥无效' })
153 return
154 }
155
156 try {
157 const body = await this.readBody(req)
158 const result = await this.routeRequest(url, body)
159 this.sendJson(res, 200, result)
160 } catch (error) {
161 console.error('[HttpServer] 请求处理失败:', error)
162 this.sendJson(res, 500, {
163 code: 500,
164 message: error instanceof Error ? error.message : '内部服务器错误'
165 })
166 }
167 }
168
169 private readBody(req: IncomingMessage): Promise<Record<string, unknown>> {
170 return new Promise((resolve, reject) => {

Callers 1

startMethod · 0.95

Calls 3

sendJsonMethod · 0.95
readBodyMethod · 0.95
routeRequestMethod · 0.95

Tested by

no test coverage detected