1 // This file is written in D programming language
2 /**
3 *   The example demonstrates how to run vibe.d server
4 *   in daemon mode.
5 *   
6 *   If SIGTERM is received, daemon terminates. If SIGHUP is received,
7 *   daemon prints "Hello World!" message to logg.
8 *
9 *   Copyright: © 2014 Anton Gushcha
10 *   License: Subject to the terms of the MIT license, as written in the included LICENSE file.
11 *   Authors: NCrashed <ncrashed@gmail.com>
12 */
13 module example03;
14 
15 import daemonize.d;
16 
17 import vibe.core.core;
18 import vibe.core.log;
19 import vibe.core.log : VibeLogLevel = LogLevel;
20 import vibe.http.server;
21 
22 // Simple daemon description
23 alias daemon = Daemon!(
24     "DaemonizeExample3", // unique name
25     
26     KeyValueList!(
27         Composition!(Signal.Terminate, Signal.Quit, Signal.Shutdown, Signal.Stop), (logger)
28         {
29             logger.logInfo("Exiting...");
30             
31             // No need to force exit here
32             // main will stop after the call 
33             exitEventLoop(true);
34             return true; 
35         },
36         Signal.HangUp, (logger)
37         {
38             logger.logInfo("Hello World!");
39             return true;
40         }
41     ),
42     
43     (logger, shouldExit) {
44         // Default vibe initialization
45         auto settings = new HTTPServerSettings;
46         settings.port = 8080;
47         settings.bindAddresses = ["127.0.0.1"];
48 
49         listenHTTP(settings, &handleRequest);
50 
51         // All exceptions are caught by daemonize
52         return runEventLoop();
53     }
54 );
55 
56 // Vibe handler
57 void handleRequest(HTTPServerRequest req,
58                    HTTPServerResponse res)
59 {
60     res.writeBody("Hello World!", "text/plain");
61 }
62 
63 int main()
64 {
65     // Setting vibe logger 
66     // daemon closes stdout/stderr and vibe logger will crash
67     // if not suppress printing to console
68     version(Windows) enum vibeLogName = "C:\\vibe.log";
69     else enum vibeLogName = "vibe.log";
70 
71     // no stdout/stderr output
72     version(Windows) {}
73     else setLogLevel(VibeLogLevel.none);
74 
75     setLogFile(vibeLogName, VibeLogLevel.info);
76 
77     version(Windows) enum logFileName = "C:\\logfile.log";
78     else enum logFileName = "logfile.log";
79 
80     auto logger = new shared DloggLogger(logFileName);
81     return buildDaemon!daemon.run(logger);
82 }