這個源碼閱讀我是想將旁支末梢先捋順了。再進入主程的application
Response與Request主要是對原生createServer的req可讀流 res可寫流作二次封裝html
/** * Prototype. */ module.exports = { /** * Return the request socket. * * @return {Connection} * @api public */ //定義一個getter 得到req.socket get socket() { return this.ctx.req.socket; }, /** * Return response header. * * @return {Object} * @api public */ //返回一個response header //這裏作了個版本的兼容 用getHeaders 來判斷版本兼容方法 get header() { const { res } = this; return typeof res.getHeaders === 'function' ? res.getHeaders() : res._headers || {}; // Node < 7.7 }, /** * Return response header, alias as response.header * * @return {Object} * @api public */ //定義一個getter 也就是headers 實際上是header的別名 get headers() { return this.header; }, /** * Get response status code. * * @return {Number} * @api public */ //定義一個seeter 用來返回res的statusCode get status() { return this.res.statusCode; }, /** * Set response status code. * * @param {Number} code * @api public */ //設置status set status(code) { assert('number' == typeof code, 'status code must be a number'); //檢測是否爲數字 assert(statuses[code], `invalid status code: ${code}`); //判斷是否存在這個狀態碼 assert(!this.res.headersSent, 'headers have already been sent'); //判斷響應是否已發送 this._explicitStatus = true; //這裏有一個私有變量 //做爲一個標記若是這個爲false後面會自動設置狀態碼 this.res.statusCode = code; //設置res.statusCode this.res.statusMessage = statuses[code]; //設置status message statuses是一些狀態碼與常見迴應的字符串例如404 :not found這種 if (this.body && statuses.empty[code]) this.body = null; //若是狀態碼不在http狀態碼內 body=null不該答 }, /** * Get response status message * * @return {String} * @api public */ //得到statusMessage不存在就根據狀態碼從statuses取 get message() { return this.res.statusMessage || statuses[this.status]; }, /** * Set response status message * * @param {String} msg * @api public */ //設置statusMessage 用的仍是res set message(msg) { this.res.statusMessage = msg; }, /** * Get response body. * * @return {Mixed} * @api public */ //getter 返回響應的body get body() { return this._body; }, /** * Set response body. * * @param {String|Buffer|Object|Stream} val * @api public */ //設置響應的body set body(val) { const original = this._body; this._body = val; //使用一個私有變量來記錄這個值 if (this.res.headersSent) return; //判斷響應體是否發送了 // no content //若是body爲空 if (null == val) { if (!statuses.empty[this.status]) this.status = 204; this.remove('Content-Type'); this.remove('Content-Length'); this.remove('Transfer-Encoding'); return; } //設置狀態碼(_explicitStatus上面有這個標記) // set the status if (!this._explicitStatus) this.status = 200; // set the content-type only if not yet set const setType = !this.header['content-type']; //根據傳入的value 進行不一樣的處理 // string if ('string' == typeof val) { if (setType) this.type = /^\s*</.test(val) ? 'html' : 'text'; this.length = Buffer.byteLength(val); return; } // buffer if (Buffer.isBuffer(val)) { if (setType) this.type = 'bin'; this.length = val.length; return; } // stream if ('function' == typeof val.pipe) { onFinish(this.res, destroy.bind(null, val)); ensureErrorHandler(val, err => this.ctx.onerror(err)); // overwriting if (null != original && original != val) this.remove('Content-Length'); if (setType) this.type = 'bin'; return; } // json //remove方法是移除header某個字段 this.remove('Content-Length'); this.type = 'json'; }, /** * Set Content-Length field to `n`. * * @param {Number} n * @api public */ //設置content-length根據傳入一個值 set length(n) { this.set('Content-Length', n); }, /** * Return parsed response Content-Length when present. * * @return {Number} * @api public */ // getter 得到content-length get length() { const len = this.header['content-length']; const body = this.body; //若是content-length爲空 //則根據咱們本身的方法來得到這個body響應體的length if (null == len) { if (!body) return; if ('string' == typeof body) return Buffer.byteLength(body); if (Buffer.isBuffer(body)) return body.length; if (isJSON(body)) return Buffer.byteLength(JSON.stringify(body)); return; } //這位運算返回一個number return ~~len; }, /** * Check if a header has been written to the socket. * * @return {Boolean} * @api public */ //返回res.headersSent get headerSent() { return this.res.headersSent; }, /** * Vary on `field`. * * @param {String} field * @api public */ /* 給vary添加field 用於代理服務器的緩存控制 * 服務器爲 Vary 設置一組 header,告訴代理服務器該如何使用緩存。 * 在後續的請求中,代理服務器只對請求中包含相同的 header 返回緩存。 */ vary(field) { vary(this.res, field); }, /** * Perform a 302 redirect to `url`. * * The string "back" is special-cased * to provide Referrer support, when Referrer * is not present `alt` or "/" is used. * * Examples: * * this.redirect('back'); * this.redirect('back', '/index.html'); * this.redirect('/login'); * this.redirect('http://google.com'); * * @param {String} url * @param {String} [alt] * @api public */ //提供302重定向 //兩個參數 一個url 一個alt //若是url爲'back'的時候咱們獲取它的Referrer來源 //在進行跳轉到這個location redirect(url, alt) { // location if ('back' == url) url = this.ctx.get('Referrer') || alt || '/'; this.set('Location', url); // status //若是不在跳轉狀態碼內就設定302 if (!statuses.redirect[this.status]) this.status = 302; // html //accept type若是爲html if (this.ctx.accepts('html')) { url = escape(url); this.type = 'text/html; charset=utf-8'; //設置一個跳轉 this.body = `Redirecting to <a href="${url}">${url}</a>.`; return; } // text //否則的話就文本描述跳轉 this.type = 'text/plain; charset=utf-8'; this.body = `Redirecting to ${url}.`; }, /** * Set Content-Disposition header to "attachment" with optional `filename`. * * @param {String} filename * @api public */ //將Content-Disposition標題設置爲可選的`filename`爲「attachment」。 //也就是說將filename包裹成咱們熟悉的acttachment;filename = xxx //用做消息主體的時候 //https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Disposition attachment(filename) { if (filename) this.type = extname(filename); this.set('Content-Disposition', contentDisposition(filename)); }, /** * Set Content-Type response header with `type` through `mime.lookup()` * when it does not contain a charset. * * Examples: * * this.type = '.html'; * this.type = 'html'; * this.type = 'json'; * this.type = 'application/json'; * this.type = 'png'; * * @param {String} type * @api public */ //設置content-type //被容許的時候爲添加,不被容許爲刪除 set type(type) { type = getType(type); if (type) { this.set('Content-Type', type); } else { this.remove('Content-Type'); } }, //lastModified 用於web緩存的 /** * Set the Last-Modified date using a string or a Date. * * this.response.lastModified = new Date(); * this.response.lastModified = '2013-09-13'; * * @param {String|Date} type * @api public */ set lastModified(val) { if ('string' == typeof val) val = new Date(val); this.set('Last-Modified', val.toUTCString()); }, //get last-modified /** * Get the Last-Modified date in Date form, if it exists. * * @return {Date} * @api public */ get lastModified() { const date = this.get('last-modified'); if (date) return new Date(date); }, /** * Set the ETag of a response. * This will normalize the quotes if necessary. * * this.response.etag = 'md5hashsum'; * this.response.etag = '"md5hashsum"'; * this.response.etag = 'W/"123456789"'; * * @param {String} etag * @api public */ //設置etag set etag(val) { if (!/^(W\/)?"/.test(val)) val = `"${val}"`; this.set('ETag', val); }, /** * Get the ETag of a response. * * @return {String} * @api public */ //得到etag值 get etag() { return this.get('ETag'); }, /** * Return the response mime type void of * parameters such as "charset". * * @return {String} * @api public */ //得到content ;分割的前面部分 //相似這種Content-Type: multipart/form-data;boundary=something get type() { const type = this.get('Content-Type'); if (!type) return ''; return type.split(';')[0]; }, /** * Check whether the response is one of the listed types. * Pretty much the same as `this.request.is()`. * * @param {String|Array} types... * @return {String|false} * @api public */ is(types) { const type = this.type; if (!types) return type || false; if (!Array.isArray(types)) types = [].slice.call(arguments); //檢查是否被容許 容許就返回對應的值 return typeis(type, types); }, /** * Return response header. * * Examples: * * this.get('Content-Type'); * // => "text/plain" * * this.get('content-type'); * // => "text/plain" * * @param {String} field * @return {String} * @api public */ //返回響應頭 //這邊獲得某個頭部信息都轉化成小寫 get(field) { return this.header[field.toLowerCase()] || ''; }, /** * Set header `field` to `val`, or pass * an object of header fields. * * Examples: * * this.set('Foo', ['bar', 'baz']); * this.set('Accept', 'application/json'); * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); * * @param {String|Object|Array} field * @param {String} val * @api public */ //設置header字段或者值 or 傳遞頭部字段的對象。 set(field, val) { if (2 == arguments.length) { if (Array.isArray(val)) val = val.map(String); else val = String(val); this.res.setHeader(field, val); } else { for (const key in field) { this.set(key, field[key]); } } }, /** * Append additional header `field` with value `val`. * * Examples: * * ``` * this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']); * this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); * this.append('Warning', '199 Miscellaneous warning'); * ``` * * @param {String} field * @param {String|Array} val * @api public */ //附加額外的頭部字段值 append(field, val) { const prev = this.get(field); if (prev) { val = Array.isArray(prev) ? prev.concat(val) : [prev].concat(val); } return this.set(field, val); }, //刪除頭部字段 /** * Remove header `field`. * * @param {String} name * @api public */ remove(field) { this.res.removeHeader(field); }, /** * Checks if the request is writable. * Tests for the existence of the socket * as node sometimes does not set it. * * @return {Boolean} * @api private */ //檢查請求是否可寫 get writable() { // can't write any more after response finished //判斷流是否結束 if (this.res.finished) return false; const socket = this.res.socket; // There are already pending outgoing res, but still writable // https://github.com/nodejs/node/blob/v4.4.7/lib/_http_server.js#L486 if (!socket) return true; return socket.writable; }, /** * Inspect implementation. * * @return {Object} * @api public */ //Inspect //當咱們在內部console.log(this)時候默認調用這個方法 // inspect() { if (!this.res) return; const o = this.toJSON(); o.body = this.body; return o; }, /** * Return JSON representation. * * @return {Object} * @api public */ //返回json表示 toJSON() { return only(this, [ 'status', 'message', 'header' ]); }, /** * Flush any set headers, and begin the body */ flushHeaders() { this.res.flushHeaders(); } };
/** * Prototype. */ module.exports = { //如下三個跟response類似只是對象不一樣了 get header() { return this.req.headers; }, set header(val) { this.req.headers = val; }, get headers() { return this.req.headers; }, set headers(val) { this.req.headers = val; }, //返回請求的url字符串 get url() { return this.req.url; }, // 設置url地址 用於進行 url 重寫 set url(val) { this.req.url = val; }, // getter得到origin // 請求首部字段 Origin 指示了請求來自於哪一個站點 get origin() { return `${this.protocol}://${this.host}`; }, /** * Get full request URL. * * @return {String} * @api public */ // 得到request徹底地址 get href() { // support: `GET http://example.com/foo` if (/^https?:\/\//i.test(this.originalUrl)) return this.originalUrl; return this.origin + this.originalUrl; }, //得到請求方法 get method() { return this.req.method; }, //設置請求方法 set method(val) { this.req.method = val; }, // 返回請求 pathname get path() { return parse(this.req).pathname; }, //設置pathname 若是原url有查詢字符串queryString的話會獲得保留 set path(path) { const url = parse(this.req); if (url.pathname === path) return; url.pathname = path; url.path = null; this.url = stringify(url); }, // 得到解析事後的查詢字符串 ?xxx=123&abc=878這些 get query() { const str = this.querystring; const c = this._querycache = this._querycache || {}; return c[str] || (c[str] = qs.parse(str)); }, // 設置一個對象作查詢字符串 set query(obj) { this.querystring = qs.stringify(obj); }, //返回 url 中的查詢字符串,去除了頭部的 '?' get querystring() { if (!this.req) return ''; return parse(this.req).query || ''; }, //設置查詢字符串 set querystring(str) { const url = parse(this.req); if (url.search === `?${str}`) return; url.search = str; url.path = null; this.url = stringify(url); }, //返回url中的查詢字符串包括? get search() { if (!this.querystring) return ''; return `?${this.querystring}`; }, //設置查詢字符串包含? set search(str) { this.querystring = str; }, // 得到請求主機名 不包含端口 // 若是app.proxy爲true 支持X-Forwarded-Host get host() { const proxy = this.app.proxy; let host = proxy && this.get('X-Forwarded-Host'); host = host || this.get('Host'); if (!host) return ''; return host.split(/\s*,\s*/)[0]; }, //加了個ipv6支持 get hostname() { const host = this.host; if (!host) return ''; if ('[' == host[0]) return this.URL.hostname || ''; // IPv6 return host.split(':')[0]; }, /** * Get WHATWG parsed URL. * Lazily memoized. * * @return {URL|Object} * @api public */ //這是一個新加的 //由於之前的一些[::]:80解析出錯 //就使用這個作解析 //https://github.com/koajs/koa/commit/327b65cb6b86e31285cbe5c423505da15ca589f6 get URL() { if (!this.memoizedURL) { const protocol = this.protocol; const host = this.host; const originalUrl = this.originalUrl || ''; // avoid undefined in template string try { this.memoizedURL = new URL(`${protocol}://${host}${originalUrl}`); } catch (err) { this.memoizedURL = Object.create(null); } } return this.memoizedURL; }, //檢查請求是否足夠新 也就是檢查Last-Modified(和/或)ETag仍然匹配 //當緩存爲最新時,可編寫業務邏輯直接返回 304 get fresh() { const method = this.method; const s = this.ctx.status; // GET or HEAD for weak freshness validation only if ('GET' != method && 'HEAD' != method) return false; // 2xx or 304 as per rfc2616 14.26 if ((s >= 200 && s < 300) || 304 == s) { return fresh(this.header, this.ctx.response.header); } return false; }, //檢查若是請求過期了,又稱爲"Last-Modified" and / or the "ETag"資源被改變 get stale() { return !this.fresh; }, //檢查請求是不是冪等的。 //一個冪等操做的特色是其任意屢次執行所產生的影響均與一次執行的影響相同 get idempotent() { const methods = ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS', 'TRACE']; return !!~methods.indexOf(this.method); }, //返回request資源連接socket get socket() { return this.req.socket; }, //當存在或未定義時獲取charset。 //content-type:text/html; charset=utf-8 get charset() { let type = this.get('Content-Type'); if (!type) return ''; try { type = contentType.parse(type); } catch (e) { return ''; } return type.parameters.charset || ''; }, /** * Return parsed Content-Length when present. * * @return {Number} * @api public */ //返回content-length //返回一個number get length() { const len = this.get('Content-Length'); if (len == '') return; return ~~len; }, /** * Return the protocol string "http" or "https" * when requested with TLS. When the proxy setting * is enabled the "X-Forwarded-Proto" header * field will be trusted. If you're running behind * a reverse proxy that supplies https for you this * may be enabled. * * @return {String} * @api public */ /* * 若是socket被加密了直接返回https * 返回協議字符串http或者https當請求是使用TLS(傳輸層安全協議),當proxy代理設置被支持X-Forwarded-Proto頭部 * 字段,若是你運行了一個反向代理爲你提供https 這也許能夠被支持 */ get protocol() { const proxy = this.app.proxy; if (this.socket.encrypted) return 'https'; if (!proxy) return 'http'; const proto = this.get('X-Forwarded-Proto') || 'http'; return proto.split(/\s*,\s*/)[0]; }, /** * Short-hand for: * * this.protocol == 'https' * * @return {Boolean} * @api public */ //'https' == this.protocol; get secure() { return 'https' == this.protocol; }, /** * When `app.proxy` is `true`, parse * the "X-Forwarded-For" ip address list. * * For example if the value were "client, proxy1, proxy2" * you would receive the array `["client", "proxy1", "proxy2"]` * where "proxy2" is the furthest down-stream. * * @return {Array} * @api public */ /* 當app.proxy爲true的時候 解析X-Forwarded-For ip地址列表 * 例如若是那個值爲 client, proxy1, proxy2 * 你會獲得一個數組 其中」proxy2「是最遠的下游。 */ get ips() { const proxy = this.app.proxy; const val = this.get('X-Forwarded-For'); return proxy && val ? val.split(/\s*,\s*/) : []; }, /* * 返回請求對象中的子域名數組。子域名數組會自動由請求域名字符串中的 . 分割開, * 在沒有設置自定義的 app.subdomainOffset 參數時,默認返回根域名以前的全部子域名數組。 * 得到子域 */ get subdomains() { const offset = this.app.subdomainOffset; const hostname = this.hostname; if (net.isIP(hostname)) return []; return hostname .split('.') .reverse() .slice(offset); }, /** * Check if the given `type(s)` is acceptable, returning * the best match when true, otherwise `false`, in which * case you should respond with 406 "Not Acceptable". * * The `type` value may be a single mime type string * such as "application/json", the extension name * such as "json" or an array `["json", "html", "text/plain"]`. When a list * or array is given the _best_ match, if any is returned. * * Examples: * * // Accept: text/html * this.accepts('html'); * // => "html" * * // Accept: text/*, application/json * this.accepts('html'); * // => "html" * this.accepts('text/html'); * // => "text/html" * this.accepts('json', 'text'); * // => "json" * this.accepts('application/json'); * // => "application/json" * * // Accept: text/*, application/json * this.accepts('image/png'); * this.accepts('png'); * // => false * * // Accept: text/*;q=.5, application/json * this.accepts(['html', 'json']); * this.accepts('html', 'json'); * // => "json" * * @param {String|Array} type(s)... * @return {String|Array|false} * @api public */ /* * 檢測type是否合法 * 匹配返回你想要的值默認返回所有 * 當請求頭中不包含 Accept 屬性時,給定的第一個 type 將會被返回。 */ accepts(...args) { return this.accept.types(...args); }, /** * 返回一個可接受的編碼。優先級以下 * 也能夠指定返回沒有就返回false * ['gzip', 'deflate'] */ acceptsEncodings(...args) { return this.accept.encodings(...args); }, /* *返回被接收的charset或最適合基於charsets的 * Return accepted charsets or best fit based on `charsets`. * 判斷客戶端是否接受給定的編碼方式的快捷方法,當有傳入參數時,返回最應當返回的一種編碼方式。 * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` * an array sorted by quality is returned: * 優先級是這個 也能夠指定 * ['utf-8', 'utf-7', 'iso-8859-1'] * 返回就是返回一個 沒有就返回false * 當沒有傳入參數時,返回客戶端的請求數組: */ //接受的字符集 acceptsCharsets(...args) { return this.accept.charsets(...args); }, /**返回被接受的語言 * Return accepted languages or best fit based on `langs`. * * Given `Accept-Language: en;q=0.8, es, pt` * an array sorted by quality is returned: * 優先級爲下面這個 * ['es', 'pt', 'en'] * 返回就是返回一個 沒有就返回false */ acceptsLanguages(...args) { return this.accept.languages(...args); }, /**檢查是否包含Content-Type頭域 而且包含任何給予mime type的任何內容 * 若是沒有請求體就返回空 若是沒有內容類型就返回false 否則就返回匹配的第一個type * 判斷請求對象中 Content-Type 是否爲給定 type 的快捷方法,若是不存在 request.body,將返回 undefined, * 若是沒有符合的類型,返回 false,除此以外,返回匹配的類型字符串。 */ //檢查響應是否是被容許的 與this.request.is()相同 is(types) { if (!types) return typeis(this.req); if (!Array.isArray(types)) types = [].slice.call(arguments); //檢查是否被容許 容許就返回對應的值 return typeis(this.req, types); //判斷是否存在type存在的話返回那個type不存在的話返回Boolean }, /** * Return the request mime type void of * parameters such as "charset". * * @return {String} * @api public */ //獲取頭部Content-type值(內容的格式) get type() { const type = this.get('Content-Type'); if (!type) return ''; return type.split(';')[0]; }, /** * Return request header. * * The `Referrer` header field is special-cased, * both `Referrer` and `Referer` are interchangeable. * * Examples: * * this.get('Content-Type'); * // => "text/plain" * * this.get('content-type'); * // => "text/plain" * * this.get('Something'); * // => undefined * * @param {String} field * @return {String} * @api public */ //獲取某個頭部字段 get(field) { const req = this.req; switch (field = field.toLowerCase()) { case 'referer': case 'referrer': return req.headers.referrer || req.headers.referer || ''; default: return req.headers[field] || ''; } }, //這個方法的做用是這樣的 //class test(){ // inspect(){ // return 'xixi' // } //} //console.log(new test()) //也就是返回這個對象的JSON格式啦 //相似util.inspect inspect() { if (!this.req) return; return this.toJSON(); }, /** * Return JSON representation. * * @return {Object} * @api public */ toJSON() { return only(this, [ 'method', 'url', 'header' ]); } };