Mochiweb custom configuration
Question
I have tried to search for an answer in google, and this site, but it seems I cannot find anywhere, so I decided to ask.
I'm planning of using mochiweb as my webserver, and I studied it for few days now. My question is simple:
Where could I put or add a custom configuration? (e.g. Database connection setting), so mochiweb could load it and processing it?
Thanks Bromo
Solution
What I did, was:
- I create a new folder inside priv, called: config
- I put my config file there
I add a line inside mochiweb_sup.erl like below, to put my config folder as part of the parameters that will be passed to mochiweb_web.erl module:
web_spec(Mod, Port) -> WebConfig = [{ip, {0,0,0,0}, {port, Port}, %% my code is below {docroot, something_deps:local_path(["priv", "www"])}, {custom_config, something_deps:local_path(["priv", "config"])}], ...
Than I read that additional path from mochiweb_web.erl module like below
start(Options) -> {DocRoot, Options1} = get_option(docroot, Options), %% my code is below {ConfigPath, Options2} = get_option(custom_config, Options1), %% loading my config file {ok, FileHandler} = get_config_file(ConfigPath), ...
Then I load my custom config file by creating a function as below:
get_config_file(ConfigPath) -> FileName = "custom_config.txt", case file:consult(filename:join([ConfigPath, FileName])) of {ok, FileHandler} -> {ok, FileHandler}; {error, Reason} -> {error, Reason} end.
That's it! now you can further process that config file as you like. If you want to process the config, I suggest you to process it inside the start(Options) block, and before mochiweb_http:start function executed, so if you need to pass the result, you can pass it as part of the arguments in mochiweb_http:start, but that means you need to extend the mochiweb_http:start function in mochiweb_http.erl module.
Thanks.