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")) } } }