1
1
const http = require ( "http" ) ;
2
+ const https = require ( "https" ) ;
2
3
var url = require ( "url" ) ;
3
4
const StringDecoder = require ( "string_decoder" ) . StringDecoder
5
+ var config = require ( './config' ) ;
6
+ var fs = require ( 'fs' ) ;
4
7
5
- const server = http . createServer ( function ( req , res ) {
8
+ const unifiedServer = function ( req , res ) {
6
9
const {
7
10
pathname : path ,
8
11
query : queryStringObj
@@ -30,6 +33,7 @@ const server = http.createServer(function(req, res) {
30
33
statusCode = typeof ( statusCode ) == 'number' ? statusCode : 200 ;
31
34
payload = typeof ( payload ) == 'object' ? payload : { } ;
32
35
var payloadString = JSON . stringify ( payload )
36
+ res . setHeader ( 'Content-type' , 'application/json' ) ;
33
37
res . writeHead ( statusCode )
34
38
res . end ( payloadString )
35
39
console . log ( `request received on path: ${ trimmedPath }
@@ -39,24 +43,40 @@ const server = http.createServer(function(req, res) {
39
43
${ statusCode } and payload: ${ payloadString } ` ) ;
40
44
} )
41
45
} )
46
+ }
47
+
48
+ const httpServer = http . createServer ( unifiedServer )
49
+
50
+ httpServer . listen ( config . httpPort , function ( ) {
51
+ console . log ( `Server is listening on port ${ config . httpPort } in ${ config . envName } mode.` )
42
52
} )
53
+ const httpsServerOptions = {
54
+ key : fs . readFileSync ( './https/key.pem' ) ,
55
+ cert : fs . readFileSync ( './https/cert.pem' )
56
+ }
57
+ const httpsServer = https . createServer ( httpsServerOptions , unifiedServer )
43
58
44
- server . listen ( 3000 , function ( ) {
45
- console . log ( " Server is listening on port 3000 now." )
59
+ httpsServer . listen ( config . httpsPort , function ( ) {
60
+ console . log ( ` Server is listening on port ${ config . httpsPort } in ${ config . envName } mode.` )
46
61
} )
47
62
48
63
// Define handlers
49
64
const handlers = { }
50
65
51
- handlers . sample = function ( data , callback ) {
52
- callback ( 406 , { name : 'Sample Handler' } )
66
+ handlers . ping = function ( data , callback ) {
67
+ callback ( 200 )
68
+ }
69
+
70
+ handlers . hello = function ( data , callback ) {
71
+ callback ( 200 , { message : `Welcome: ${ data . queryStringObj . name ? data . queryStringObj . name : 'Home' } ` } )
53
72
}
54
73
55
74
// Not Found Handler
56
- handlers . notFound = function ( data , callback ) {
75
+ handlers . notFound = function ( _data , callback ) {
57
76
callback ( 404 ) ;
58
77
}
59
78
// Defining request router
60
79
const router = {
61
- 'sample' : handlers . sample
80
+ 'ping' : handlers . ping ,
81
+ 'hello' : handlers . hello
62
82
}
0 commit comments