浏览代码

feature:添加 swagger 支持

liuyaqi 3 年之前
父节点
当前提交
ada89be7fc

+ 4 - 0
handler/test.go

@@ -22,5 +22,9 @@ func (s *TestController) Nullable(ctx context.Context, req *Nullable, rsp *comm_
 	fmt.Printf("%v \n", req.Int)
 	fmt.Printf("%v \n", req.Int)
 	fmt.Printf("%v \n", req.Bool)
 	fmt.Printf("%v \n", req.Bool)
 	fmt.Printf("%v \n", req.Slice)
 	fmt.Printf("%v \n", req.Slice)
+	rsp.Code = 200
+	rsp.Msg = "success"
+	rsp.Data = nil
+	fmt.Printf("%v \n", rsp)
 	return nil
 	return nil
 }
 }

+ 12 - 0
main.go

@@ -5,6 +5,7 @@ import (
 	"github.com/golang/glog"
 	"github.com/golang/glog"
 	"lims_adapter/handler"
 	"lims_adapter/handler"
 	"lims_adapter/service/timers"
 	"lims_adapter/service/timers"
+	"net/http"
 
 
 	_ "lims_adapter/boot"
 	_ "lims_adapter/boot"
 
 
@@ -15,6 +16,7 @@ import (
 )
 )
 
 
 func main() {
 func main() {
+	go swaggerui()
 	// 定时任务
 	// 定时任务
 	c := cron.New()
 	c := cron.New()
 	spec := "0 0 1 * * ?" // 每日1点执行
 	spec := "0 0 1 * * ?" // 每日1点执行
@@ -56,3 +58,13 @@ func main() {
 func handleAuth(ctx context.Context, req *protocol.Message, token string) error {
 func handleAuth(ctx context.Context, req *protocol.Message, token string) error {
 	return micro_srv.HandleAuth(ctx, req, token, nil)
 	return micro_srv.HandleAuth(ctx, req, token, nil)
 }
 }
+
+func swaggerui() {
+	defer func() {
+		if r := recover(); r != nil {
+			glog.Error(r)
+		}
+	}()
+	glog.Error(http.ListenAndServe(":8080",
+		http.FileServer(http.Dir("./swaggerui/"))))
+}

二进制
swaggerui/favicon-16x16.png


二进制
swaggerui/favicon-32x32.png


+ 88 - 0
swaggerui/index.html

@@ -0,0 +1,88 @@
+<!-- HTML for static distribution bundle build -->
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8">
+    <title>Swagger UI</title>
+    <link rel="stylesheet" type="text/css" href="swagger-ui.css" >
+    <link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
+    <link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
+    <style>
+      html
+      {
+        box-sizing: border-box;
+        overflow: -moz-scrollbars-vertical;
+        overflow-y: scroll;
+      }
+
+      *,
+      *:before,
+      *:after
+      {
+        box-sizing: inherit;
+      }
+
+      body
+      {
+        margin:0;
+        background: #fafafa;
+      }
+    </style>
+  </head>
+
+  <body>
+    <div id="swagger-ui"></div>
+
+    <script src="swagger-ui-bundle.js"> </script>
+    <script src="swagger-ui-standalone-preset.js"> </script>
+    <script>
+    window.onload = function() {
+      // Begin Swagger UI call region
+      const ui = SwaggerUIBundle({
+        url: "./swagger.yml",
+        dom_id: '#swagger-ui',
+        deepLinking: true,
+        presets: [
+          SwaggerUIBundle.presets.apis,
+          SwaggerUIStandalonePreset
+        ],
+        plugins: [
+          SwaggerUIBundle.plugins.DownloadUrl
+        ],
+        layout: "StandaloneLayout",
+        // 设置 token
+        requestInterceptor: (req) => {
+          if (req.url == "./swagger.yml") {
+            return
+          }
+          console.log(req)
+          let serviceUrl = "http://192.168.0.102:9981/dashoo.lims.adapter-0.1-jlw"
+          let reqUrl = new URL(req.url)
+          let urlInfo = reqUrl.pathname.substring(1).split('.')
+          if (urlInfo.length < 2) {
+            return
+          }
+          let servicePath = urlInfo[0]
+          let serviceMethod = urlInfo[1]
+          let token = req.headers.Authorization
+          if (!token) {
+            token = "Bearer ajg7o1Dts1JrKCm6VtgyuuaYbUIiirXxI5+6WzYnC7gWl+43NdKq6LbWxU1zWhsBaL0A/CIkBoefM0vuu6h4ZA=="
+          }
+
+          req.url = serviceUrl
+          req.headers["X-RPCX-SerializeType"] = "1"
+          req.headers["X-RPCX-ServicePath"] = servicePath
+          req.headers["X-RPCX-ServiceMethod"] = serviceMethod
+          req.headers["Tenant"] = "EmGVD5szuT"
+          req.headers["Authorization"] = token
+          req.headers["SrvEnv"] = "dev"
+          return req
+        }
+      })
+      // End Swagger UI call region
+
+      window.ui = ui
+    }
+  </script>
+  </body>
+</html>

+ 68 - 0
swaggerui/oauth2-redirect.html

@@ -0,0 +1,68 @@
+<!doctype html>
+<html lang="en-US">
+<title>Swagger UI: OAuth2 Redirect</title>
+<body onload="run()">
+</body>
+</html>
+<script>
+    'use strict';
+    function run () {
+        var oauth2 = window.opener.swaggerUIRedirectOauth2;
+        var sentState = oauth2.state;
+        var redirectUrl = oauth2.redirectUrl;
+        var isValid, qp, arr;
+
+        if (/code|token|error/.test(window.location.hash)) {
+            qp = window.location.hash.substring(1);
+        } else {
+            qp = location.search.substring(1);
+        }
+
+        arr = qp.split("&")
+        arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';})
+        qp = qp ? JSON.parse('{' + arr.join() + '}',
+                function (key, value) {
+                    return key === "" ? value : decodeURIComponent(value)
+                }
+        ) : {}
+
+        isValid = qp.state === sentState
+
+        if ((
+          oauth2.auth.schema.get("flow") === "accessCode"||
+          oauth2.auth.schema.get("flow") === "authorizationCode"
+        ) && !oauth2.auth.code) {
+            if (!isValid) {
+                oauth2.errCb({
+                    authId: oauth2.auth.name,
+                    source: "auth",
+                    level: "warning",
+                    message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"
+                });
+            }
+
+            if (qp.code) {
+                delete oauth2.state;
+                oauth2.auth.code = qp.code;
+                oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
+            } else {
+                let oauthErrorMsg
+                if (qp.error) {
+                    oauthErrorMsg = "["+qp.error+"]: " +
+                        (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
+                        (qp.error_uri ? "More info: "+qp.error_uri : "");
+                }
+
+                oauth2.errCb({
+                    authId: oauth2.auth.name,
+                    source: "auth",
+                    level: "error",
+                    message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
+                });
+            }
+        } else {
+            oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
+        }
+        window.close();
+    }
+</script>

+ 11 - 0
swaggerui/server.go

@@ -0,0 +1,11 @@
+package main
+
+import (
+	"log"
+	"net/http"
+)
+
+func main() {
+	log.Fatal(http.ListenAndServe(":8080",
+		http.FileServer(http.Dir("./swaggerui/"))))
+}

文件差异内容过多而无法显示
+ 0 - 0
swaggerui/swagger-ui-bundle.js


文件差异内容过多而无法显示
+ 0 - 0
swaggerui/swagger-ui-bundle.js.map


文件差异内容过多而无法显示
+ 0 - 0
swaggerui/swagger-ui-standalone-preset.js


文件差异内容过多而无法显示
+ 0 - 0
swaggerui/swagger-ui-standalone-preset.js.map


文件差异内容过多而无法显示
+ 1 - 0
swaggerui/swagger-ui.css


文件差异内容过多而无法显示
+ 0 - 0
swaggerui/swagger-ui.css.map


文件差异内容过多而无法显示
+ 0 - 0
swaggerui/swagger-ui.js


文件差异内容过多而无法显示
+ 0 - 0
swaggerui/swagger-ui.js.map


+ 79 - 0
swaggerui/swagger.yml

@@ -0,0 +1,79 @@
+openapi: 3.0.0
+info:
+    title: learning
+    description: 培训考试
+    version: 0.0.1
+
+paths:
+    /Test.Nullable:
+      post:
+        operationId: Test.Nullable
+        summary: 测试空值参数
+        requestBody:
+          required: true
+          content:
+            application/json:
+              schema:
+                oneOf:
+                  - $ref: '#/components/schemas/Nullable'
+              examples:
+                AllPass:
+                  $ref: '#/components/examples/NullableReqAllPass'
+        responses:
+          200:
+            description: 请求成功
+            content:
+              application/json:
+                examples:
+                  success:
+                    $ref: "#/components/examples/success"
+
+# 添加这个 swagger ui 会显示授权按钮
+security:
+  - bearerAuth: []
+
+components:
+  securitySchemes:
+    basicAuth:
+      type: http
+      scheme: basic
+    bearerAuth:
+        type: http
+        scheme: bearer
+  schemas:
+    Nullable:
+      type: object
+      required:
+        - Str
+        - Int
+        - Bool
+        - Slice
+      properties:
+        Str:
+          type: string
+          description: 字符串参数
+        Int:
+          type: integer
+          description: Int 参数
+        Bool:
+          type: boolean
+          description: Bool 参数
+        Slice:
+          type: array
+          description: Slice 参数
+          items:
+            type: integer
+
+  examples:
+    success:
+      summary: 请求成功
+      value:
+        code: 200,
+        msg: "success"
+
+    NullableReqAllPass:
+      value:
+          Str: ""
+          Int: 0
+          Bool: false
+          Slice: []

部分文件因为文件数量过多而无法显示