You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

120 lines
2.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package SwagMock
import (
"bytes"
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
type Options struct {
Host string
Port int
}
var generator *StubGenerator
//Swagger Mock 服务初始化【没有使用Middleware Handler 机制】
func Init(r *gin.Engine) {
generator, _= NewStubGenerator("docs/swagger.json", StubGeneratorOptions{
Overlay: "",
BasePath: "",
})
for path,pathItem := range generator.spec.Paths.Paths{
if pathItem.Get !=nil{
r.GET("/mock" + path, func(c *gin.Context) {
ValidJsonIn(c.Writer,c.Request)
MockJsonOut(c.Writer,c.Request)
})
}
if pathItem.Post !=nil{
r.POST("/mock" + path, func(c *gin.Context) {
ValidJsonIn(c.Writer,c.Request)
MockJsonOut(c.Writer,c.Request)
})
}
}
}
//返回Mock Json数据【根据 Swagger Spec】
func MockJsonOut(res http.ResponseWriter, req *http.Request) {
//获取json文件如果成功直接返回json文件内容
strJson,err:= ioutil.ReadFile("docs" + req.URL.Path + ".json")
if err ==nil{
res.Header().Set("Content-Type", "application/json")
//err = json.NewEncoder(res).Encode(strJson)
res.Write(strJson)
return
}
//根据Swagger Spec解析生成随机json内容
response, err := generator.StubResponse(req.URL.Path[5:], req.Method)
if err != nil {
log.Println(errors.Wrap(err, "unable to stub response"))
http.Error(res, "stub server error - check the logs", http.StatusInternalServerError)
return
}
//使用随机内容创建json文件路径为docs/root_path/api_name.json
var buf bytes.Buffer
json.NewEncoder(&buf).Encode(response)
os.MkdirAll("docs" + req.URL.Path[0:strings.LastIndex(req.URL.Path,"/")],0666)
err = ioutil.WriteFile("docs" + req.URL.Path + ".json",buf.Bytes(),0666)
if err != nil {
log.Println(errors.Wrap(err, "Mock Error: creating json temp file"))
}
//返回随机生成的json内容
res.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(res).Encode(response)
if err != nil {
log.Println(errors.Wrap(err, "unable to serialize generated response stub"))
http.Error(res, "stub server error - check the logs", http.StatusInternalServerError)
return
}
}
//验证 调用参数是否合法【根据 Swagger Spec】
func ValidJsonIn(res http.ResponseWriter, req *http.Request) {
switch req.Method {
case "POST", "GET":
operation, err := generator.FindOperation(req.URL.Path[5:], req.Method)
if err != nil {
log.Println(errors.Wrap(err, "finding operation schema for path and method"))
break
}
err = ValidateConsumes(*operation, *req)
if err != nil {
log.Println(errors.Wrap(err, "validating content type header"))
}
err = ValidateParameters(*operation, *req)
if err != nil {
log.Println(errors.Wrap(err, "validating parameters"))
}
}
}