webmachine

来源:互联网 发布:淘宝网汉服女装 编辑:程序博客网 时间:2024/05/16 18:24

公司里在搞ejabberd,公司里的头头们都是做php的,对于erlang这门语言,或多或少会有一些阅读的阻碍,故让我整理些相关的文档,也是同事的推荐,让我有了将最近研究的东西整理成一个专门的博客的想法,以备日后查阅。

       废话不多少,开始搞

       系统:ubuntu

       gitclone git://github.com/basho/webmachine.git

       cdwebmachine

       ./scripts/new_webmachine.shweb

      然后将会在你的当前目录scripts目录下生成一个web文件夹,这个文件夹就将是你要开发的项目,随后将这个web文件夹考到你的开发环境中例如我的:/data/project/webmachine 

     之后就可以将原先从github上下载下拉的那个webmachine删掉了,编译自己的项目时webmachine会被重新下载(rebar的项目开发集成方案)

     进入自己的项目

     make   webmachine会被重新集成到自己的项目中的deps目录

     vimstart.sh 

     #!/bin/sh
   cd `dirname $0`
    exec erl -name api@localhost-noshell +K true +P 1500000 -setcookie helaoshi -pa $PWD/ebin$PWD/deps/*/ebin -boot start_sasl -s reloader -s web &

    加上节点名字,使进程后台运行,并且增加一些优化配置(当然不该也可以)

    vimsrc/web.app.src

%%-*-mode: erlang -*-
{application, web,
 [
 {description, "web"},
  {vsn, "1"},
 {modules, []},
  {registered, []},
  {applications,[
                 kernel,
                 stdlib,
                 inets,
                 crypto,
                 mochiweb,
                 webmachine
                ]},
  {mod, { web_app, []}},
  {env, [
     {web_ip, "0.0.0.0"},
     {web_port, 8080}
  ]}
 ]}.
~     
可以看到自己ip和监听的端口的配置自己可以按需求更改

./start.sh便可启动自己的服务

访问 loaclhost:8080

Hello,new world

该字符串是web_resource.erl文件输出的

编辑使支持post

-module(web_resource).

-export([

init/1,

content_types_provided/2,

process_post/2,

allowed_methods/2,

to_html/2,

to_text/2

]).


-include_lib("webmachine/include/webmachine.hrl").


-specinit(list())->{ok, term()}.

init([])->

{ok,undefined}.


content_types_provided(ReqData,Context)->

{[{"text/html",to_html},{"text/plain",to_text}],ReqData,Context}.


%%%

%处理get请求

-specto_html(wrq:reqdata(), term()) ->{iodata(), wrq:reqdata(), term()}.

to_html(ReqData,State)->

{"<html><body>Hello,new world</body></html>",ReqData,State}.

to_text(ReqData,Context)->

Path= wrq:disp_path(ReqData),

Body= io_lib:format("Hello~sfrom webmachine.~n",[Path]),

{Body,ReqData,Context}.

%%处理post

process_post(ReqData,Context)->

Body= wrq:req_body(ReqData),

io:format("_body~p",[Body]),

{true,ReqData,Context}.


allowed_methods(ReqData,Context)->

{['HEAD','GET', 'PUT', 'DELETE', 'POST'], ReqData,Context}.



可以有多个访问路径此配置在

web_config.erl


dispatch()->

lists:flatten([

{[],web_resource, []}

]).


表示直接访问是web_resource.erl处理,也可自行在列表里加上{[“app”,”*”]new_resource,[]}

就可让localhost8080/app的请求让new_resource.erl处理

(以上只是使用方法,具体原理可以看webmachine源码,以后会慢慢补充)

0 0