1 | const http = require('http'); |
2 | const fs = require('fs'); |
3 | const config = require('./config'); |
4 | const pathFix = require('./pathFix'); |
5 | const template = require('./templates'); |
6 | const pages = require('./pages'); |
7 |
|
8 | const listenerFunction = function(request, response) { |
9 | if (request.url in config.static) { // static file |
10 | response.setHeader('Content-Type', config.static[request.url].type); |
11 | response.writeHead(200); |
12 | response.write(fs.readFileSync(pathFix(config.static[request.url].path), 'utf-8')); |
13 | response.end(); |
14 | return; |
15 | } |
16 | if (request.url == '/') { // index |
17 | response.setHeader('Content-Type', 'text/html'); |
18 | response.writeHead(200); |
19 | response.write(pages.index()); |
20 | response.end(); |
21 | return; |
22 | } |
23 | if (request.url.match('^\/.*\/[0-9]*$')) { // /reponame/pagenumber |
24 | repositoryName = request.url.split('/')[1]; |
25 | if (repositoryName in config.repositories) { |
26 | pageNumber = parseInt(request.url.split('/')[2]); |
27 | if (pageNumber > 0) { |
28 | page = pages.repository(repositoryName, pageNumber); |
29 | if (page) { |
30 | response.setHeader('Content-Type', 'text/html'); |
31 | response.writeHead(200); |
32 | response.write(page); |
33 | } else { |
34 | response.writeHead(404); |
35 | } |
36 | response.end(); |
37 | return; |
38 | } |
39 | } |
40 | } |
41 | if (request.url.match('^\/.*\/[0-9a-f]{40}$')) { |
42 | repositoryName = request.url.split('/')[1]; |
43 | if (repositoryName in config.repositories) { |
44 | hash = request.url.split('/')[2]; |
45 | page = pages.commit(repositoryName, hash); |
46 | if (page) { |
47 | response.setHeader('Content-Type', 'text/html'); |
48 | response.writeHead(200); |
49 | response.write(page); |
50 | } else { |
51 | response.writeHead(404); |
52 | } |
53 | response.end(); |
54 | return; |
55 | } |
56 | } |
57 | response.writeHead(404); |
58 | response.end(); |
59 | return; |
60 | } |
61 |
|
62 | const server = http.createServer(listenerFunction); |
63 | server.listen(config.port); |
64 |
|