isHttp2.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. var debug = require('debug')('ylt:isHttp2');
  2. var url = require('url');
  3. var Q = require('q');
  4. var http2 = require('is-http2');
  5. var isHttp2 = function() {
  6. 'use strict';
  7. this.check = function(data) {
  8. debug('Starting to check for HTTP2 support...');
  9. return this.checkHttp2(data)
  10. .then(function(result) {
  11. if (result.isHttp) {
  12. debug('The website is not even in HTTPS');
  13. data.toolsResults.http2 = {
  14. metrics: {
  15. http2: false
  16. }
  17. };
  18. } else if (result.isHttp2) {
  19. debug('HTTP/2 (or SPDY) is supported');
  20. data.toolsResults.http2 = {
  21. metrics: {
  22. http2: true
  23. }
  24. };
  25. } else {
  26. debug('HTTP/2 is not supported');
  27. data.toolsResults.http2 = {
  28. metrics: {
  29. http2: false
  30. }
  31. };
  32. }
  33. // Add the supported protocols as offenders
  34. if (result.supportedProtocols) {
  35. debug('Supported protocols: ' + result.supportedProtocols.join(' '));
  36. data.toolsResults.http2.offenders = {
  37. http2: result.supportedProtocols
  38. };
  39. }
  40. debug('End of HTTP2 support check');
  41. return data;
  42. })
  43. .fail(function() {
  44. return data;
  45. });
  46. };
  47. this.getParsedUrl = function(data) {
  48. return url.parse(data.toolsResults.phantomas.url);
  49. };
  50. this.getProtocol = function(data) {
  51. return this.getParsedUrl(data).protocol;
  52. };
  53. this.getDomain = function(data) {
  54. return this.getParsedUrl(data).hostname;
  55. };
  56. this.checkHttp2 = function(data) {
  57. var deferred = Q.defer();
  58. // Check if it's HTTPS first
  59. if (this.getProtocol(data) === 'http:') {
  60. deferred.resolve({
  61. isHttp: true
  62. });
  63. } else {
  64. // To make is-http2 work, you need to have openssl in a version greater than 1.0.0 installed and available in your $path.
  65. http2(this.getDomain(data), {includeSpdy: true})
  66. .then(function(result) {
  67. deferred.resolve(result);
  68. })
  69. .catch(function(error) {
  70. debug('Error while checking HTTP2 support:');
  71. debug(error);
  72. deferred.reject('Error while checking for HTTP2 support');
  73. });
  74. }
  75. return deferred.promise;
  76. };
  77. };
  78. module.exports = new isHttp2();