提供微服务(Service)
创建微服务上下文(Context)
一般在Module_Start
中调用WA_InitRestful
创建微服务上下文
RESTFUL_CONTEXT
WA_InitRestful(BROKER_HANDLE broker, MODULE_HANDLE module, const char * module_name);
注册资源
使用资源URI的匹配字符串,实现函数注册一个资源对象
// register the url that this plugin will serve and handling function
//* url match patterns:
// * sample 1: /abcd, match "/abcd" only
// * sample 2: /abcd/ match match "/abcd" and "/abcd/*"
// * sample 3: /abcd*, match any url started with "/abcd"
// * sample 4: /abcd/*, exclude "/abcd"
void WA_RegisterResource(RESTFUL_CONTEXT context, const char * url,
WA_Resource_Handler handler,
rest_action_t action);
实现资源函数
实现上一步注册资源时所提供的资源实现函数:
typedef void (*WA_Resource_Handler) (restful_request_t *request, REQ_ENV_HANDLE req_env);
其中参数request
是所收到的微服务请求,其格式如下:
typedef struct _restful_request
{
rest_action_t action;
wa_format_type_t payload_fmt;
int payload_len;
char * payload;
char * url;
char * query;
restful_ex_t * ex; // normally is NULL
}restful_request_t;
参数req_env
是对于插件不透明的句柄。
同步发送Response
在资源的实现函数中,如果当场完成了请求的处理,调用以下函数将回复消息交给框架发送:
void wa_set_response(REQ_ENV_HANDLE env, int status, wa_format_type_t fmt, int payload_len, const char* payload);
// 如果payload是空,可调用下面函数
void wa_set_response_status(REQ_ENV_HANDLE env, int status);
异步发送Response
在资源的实现函数中,可能本函数内部不能立即完成了请求的处理,比如需要进一步发送消息到外部设备,因此需要在未来当条件具备时再发送回复消息。
可以使用以下步骤完成:
- 在资源的实现函数中调用
wa_req_env_clone
克隆并保持req_env
参数,返回函数
REQ_ENV_HANDLE wa_req_env_clone(REQ_ENV_HANDLE req_env);
- 在条件具备后,使用克隆的
req_env
依次调用以下函数完成发送消息并释放req_env
克隆。
void wa_set_response(REQ_ENV_HANDLE env, int status, wa_format_type_t fmt, int payload_len, const char* payload);
void wa_send_response(REQ_ENV_HANDLE req_env);
void wa_req_env_destroy(REQ_ENV_HANDLE req_env);
Response数据结构与API
restful_response_t
的数据结构定义如下:
typedef struct _restful_response
{
int code;
wa_format_type_t payload_fmt;
int payload_len;
char * payload;
}restful_response_t;
相关的函数:
void wa_setup_response(restful_response_t * response,
int status,
wa_format_type_t payload_fmt,
int payload_len, void *payload);
// payload_to_clone: will be allocated internaly and copied.
restful_response_t * wa_new_response(int status, wa_format_type_t fmt, int payload_len, const char* payload_to_clone);
// The response and its owning buffer will be cloned
restful_response_t* wa_clone_response(restful_response_t * response);
// The payload will be handed over to the new allocated response. Its value is set to NULL in the function
restful_response_t* wa_new_response_handover_payload(int status, wa_format_type_t format, int payload_len, char ** payload_handover);
// The response and its owning payload will be freed.
void wa_free_response(restful_response_t * response);