test_httpApi.cpp 5.14 KB
Newer Older
xiongziliang committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/*
 * MIT License
 *
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <map>
#include <signal.h>
#include <iostream>
#include "Util/File.h"
xiongziliang committed
31
#include "Util/SSLBox.h"
xiongziliang committed
32 33
#include "Util/logger.h"
#include "Util/onceToken.h"
xiongziliang committed
34
#include "Util/NoticeCenter.h"
xiongziliang committed
35 36
#include "Network/TcpServer.h"
#include "Poller/EventPoller.h"
xiongziliang committed
37 38
#include "Common/config.h"
#include "Http/WebSocketSession.h"
xiongziliang committed
39 40

using namespace std;
xiongziliang committed
41 42
using namespace toolkit;
using namespace mediakit;
xiongziliang committed
43

xiongziliang committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
namespace mediakit {
////////////HTTP配置///////////
namespace Http {
#define HTTP_FIELD "http."
#define HTTP_PORT 80
const char kPort[] = HTTP_FIELD"port";
#define HTTPS_PORT 443
extern const char kSSLPort[] = HTTP_FIELD"sslport";
onceToken token1([](){
	mINI::Instance()[kPort] = HTTP_PORT;
	mINI::Instance()[kSSLPort] = HTTPS_PORT;
},nullptr);
}//namespace Http
}  // namespace mediakit


xiongziliang committed
60
static onceToken s_token([](){
xiongziliang committed
61
    NoticeCenter::Instance().addListener(nullptr,Broadcast::kBroadcastHttpRequest,[](BroadcastHttpRequestArgs){
xiongziliang committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        //const Parser &parser,HttpSession::HttpResponseInvoker &invoker,bool &consumed
        if(strstr(parser.Url().data(),"/api/") != parser.Url().data()){
            return;
        }
        //url以"/api/起始,说明是http api"
        consumed = true;//该http请求已被消费

        _StrPrinter printer;
        ////////////////method////////////////////
        printer << "\r\nmethod:\r\n\t" << parser.Method();
        ////////////////url/////////////////
        printer << "\r\nurl:\r\n\t" << parser.Url();
        ////////////////protocol/////////////////
        printer << "\r\nprotocol:\r\n\t" << parser.Tail();
        ///////////////args//////////////////
        printer << "\r\nargs:\r\n";
        for(auto &pr : parser.getUrlArgs()){
            printer <<  "\t" << pr.first << " : " << pr.second << "\r\n";
        }
        ///////////////header//////////////////
        printer << "\r\nheader:\r\n";
        for(auto &pr : parser.getValues()){
            printer <<  "\t" << pr.first << " : " << pr.second << "\r\n";
        }
        ////////////////content/////////////////
        printer << "\r\ncontent:\r\n" << parser.Content();
        auto contentOut = printer << endl;

        ////////////////我们测算异步回复,当然你也可以同步回复/////////////////
91
		EventPollerPool::Instance().getPoller()->async([invoker,contentOut](){
xiongziliang committed
92 93 94 95 96 97 98 99 100 101 102 103 104
            HttpSession::KeyValue headerOut;
			//你可以自定义header,如果跟默认header重名,则会覆盖之
			//默认header有:Server,Connection,Date,Content-Type,Content-Length
			//请勿覆盖Connection、Content-Length键
			//键名覆盖时不区分大小写
            headerOut["TestHeader"] = "HeaderValue";
            invoker("200 OK",headerOut,contentOut);
        });
    });
}, nullptr);

int main(int argc,char *argv[]){
	//设置退出信号处理函数
105 106 107
	static semaphore sem;
	signal(SIGINT, [](int) { sem.post(); });// 设置退出信号

xiongziliang committed
108
	//设置日志
109 110 111
	Logger::Instance().add(std::make_shared<ConsoleChannel>());
	Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());

xiongziliang committed
112
	//加载配置文件,如果配置文件不存在就创建一个
xiongziliang committed
113
	loadIniConfig();
xiongziliang committed
114 115 116 117 118 119 120

#ifdef ENABLE_OPENSSL
	//请把证书"test_httpApi.pem"放置在本程序可执行程序同目录下
	try{
		//加载证书,证书包含公钥和私钥
		SSL_Initor::Instance().loadServerPem((exePath() + ".pem").data());
	}catch(...){
xiongziliang committed
121
		ErrorL << "请把证书:" << (exeName() + ".pem") << "放置在本程序可执行程序同目录下:" << exeDir() << endl;
xiongziliang committed
122 123 124 125 126
		return 0;
	}
#endif //ENABLE_OPENSSL

	//开启http服务器
127
	TcpServer::Ptr httpSrv(new TcpServer());
xiongziliang committed
128
	httpSrv->start<EchoWebSocketSession>(mINI::Instance()[Http::kPort]);//默认80
xiongziliang committed
129 130 131

#ifdef ENABLE_OPENSSL
    //如果支持ssl,还可以开启https服务器
132
	TcpServer::Ptr httpsSrv(new TcpServer());
xiongziliang committed
133
	httpsSrv->start<SSLEchoWebSocketSession>(mINI::Instance()[Http::kSSLPort]);//默认443
xiongziliang committed
134 135 136 137
#endif //ENABLE_OPENSSL

	InfoL << "你可以在浏览器输入:http://127.0.0.1/api/my_api?key0=val0&key1=参数1" << endl;

138
	sem.wait();
xiongziliang committed
139 140 141
	return 0;
}