Moco是一個簡易的Mock Server搭建工具
Github開源鏈接:https://github.com/dreamhead/moco
一、准備工作
2.電腦需要安裝Java環境
二、運行Moco
打開terminal,運行命令
java -jar <path-to-moco-runner> http -p <monitor-port> -c < configuration -file>
<path-to-moco-runner>:moco-runner-xxx-standalone.jar包的路徑
<monitor-port>:http服務監聽的端口
<configuration -file>:配置文件路徑
示例:
三、mock.json文件編寫示例(針對http請求)
PS:一般使用Mock Server都是臨時替代正規server的作用,特別是正式的server沒有開發好的時候,所以重點是API與數據格式是否正確,一般不會作數據保存、復雜的參數校驗以及上傳數據格式校驗這些。
1. GET請求
// 普通的GET請求 { "request" : { "method" : "get", "uri" : "/api/image_management/" }, "response" : { "json" : {...} } }
// GET請求中帶ID { "request" : { "method" : "get", "uri": {"match": "/api/image_management/[0-9]*/"} }, "response" : { "json" : {...} } }
// GET請求中帶Query { "request" : { "method" : "get", "uri": { "match": "/api/image_management/list_usage/"}, "queries": { "usage": "xxx" } }, "response" : { "json" : {...} } }
2. POST 請求
// 不作上傳數據校驗,簡易的POST // Query與url中帶ID可以參考上面的GET請求,這里不再贅述 { "request" : { "method" : "post", "uri" : "/api/keys/", "headers" : { "content-type" : "application/json" } }, "response" : { "json" : {...} } }
3. PUT
// 操作大致同上面POST { "request" : { "method" : "put", "uri" : {"match": "/api/job_management/configuration/[0-9]*/"}, "headers" : { "content-type" : "application/json" } }, "response" : { "json" : {...} } }
4.DELETE
// 后面的.*可以與任意字符串作匹配 { "request" : { "method" : "delete", "uri" : {"match": "/api/job_management/instance/.*"} }, "response" : { "text" : "success" } }
跨域問題的解決:
需要給reponse設置access control
[ { "request" : { "method" : "get", "uri" : "/api/image_management/" }, "response" : { "headers" : { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods":"PUT,POST,GET,DELETE,OPTIONS", "Access-Control-Allow-Headers": "Content-Type,Content-Length, Authorization, Accept,X-Requested-With" }, "json" : ["test1", "test2", "test3"] } } ]
關於HTTP的API想要學習更多,可以前往官方文檔:https://github.com/dreamhead/moco/blob/master/moco-doc/apis.md