Skip to content

Commit

Permalink
Add ScriptSrcs to add extra scripts URLs to load
Browse files Browse the repository at this point in the history
Summary: This allows importing plugins from local and external hosts.

```
	r.Get("/swagger/*", httpSwagger.Handler(
		httpSwagger.ScriptSrc("/static/swagger-helper.js"),
		httpSwagger.ScriptSrc("https://unpkg.com/swagger-ui-plugin-disable-try-it-out-without-servers@1.0.0/build/index.js"),
		httpSwagger.Plugins([]string{"DisableTryItOutWithoutServersPlugin"},
		httpSwagger.URL("http://localhost:1323/swagger/doc.json"), //The url pointing to API definition
	))
```

Closes #83

Test Plan: Updated existing tests. Added example in example/go-chi/
  • Loading branch information
Zhomart committed Jan 13, 2023
1 parent c8d62bf commit 39c92d8
Show file tree
Hide file tree
Showing 7 changed files with 130 additions and 70 deletions.
71 changes: 13 additions & 58 deletions example/go-chi/docs/docs.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// Package docs GENERATED BY SWAG; DO NOT EDIT
// This file was generated by swaggo/swag
package docs

import (
"bytes"
"encoding/json"
"strings"
"text/template"
import "github.com/swaggo/swag"

"github.com/swaggo/swag"
)

var doc = `{
const docTemplate = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
Expand All @@ -34,56 +27,18 @@ var doc = `{
"paths": {}
}`

type swaggerInfo struct {
Version string
Host string
BasePath string
Schemes []string
Title string
Description string
}

// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = swaggerInfo{
Version: "1.0",
Host: "petstore.swagger.io",
BasePath: "/v2",
Schemes: []string{},
Title: "Swagger Example API",
Description: "This is a sample server Petstore server.",
}

type s struct{}

func (s *s) ReadDoc() string {
sInfo := SwaggerInfo
sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1)

t, err := template.New("swagger_info").Funcs(template.FuncMap{
"marshal": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
"escape": func(v interface{}) string {
// escape tabs
str := strings.Replace(v.(string), "\t", "\\t", -1)
// replace " with \", and if that results in \\", replace that with \\\"
str = strings.Replace(str, "\"", "\\\"", -1)
return strings.Replace(str, "\\\\\"", "\\\\\\\"", -1)
},
}).Parse(doc)
if err != nil {
return doc
}

var tpl bytes.Buffer
if err := t.Execute(&tpl, sInfo); err != nil {
return doc
}

return tpl.String()
var SwaggerInfo = &swag.Spec{
Version: "1.0",
Host: "petstore.swagger.io",
BasePath: "/v2",
Schemes: []string{},
Title: "Swagger Example API",
Description: "This is a sample server Petstore server.",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
}

func init() {
swag.Register(swag.Name, &s{})
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}
4 changes: 2 additions & 2 deletions example/go-chi/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ require (
github.com/go-chi/chi v4.1.2+incompatible
github.com/swaggo/http-swagger v1.2.6
github.com/swaggo/swag v1.8.1
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect
golang.org/x/tools v0.1.10 // indirect
)

replace github.com/swaggo/http-swagger => ../../
16 changes: 6 additions & 10 deletions example/go-chi/go.sum
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs=
github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY=
Expand All @@ -18,10 +16,12 @@ github.com/go-chi/chi v4.1.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxm
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=
github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=
github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=
github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA=
github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo=
github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=
github.com/go-openapi/spec v0.20.6 h1:ich1RQ3WDbfoeTqTAb+5EIxNmpKVJZWBNah9RAT0jIQ=
github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
Expand Down Expand Up @@ -59,11 +59,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 h1:+iNTcqQJy0OZ5jk6a5NLib47eqXK8uYcPX+O4+cBpEM=
github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w=
github.com/swaggo/http-swagger v1.2.6 h1:ihTjChUoSRMpFMjWw+0AkL1Ti4r6v8pCgVYLmQVRlRw=
github.com/swaggo/http-swagger v1.2.6/go.mod h1:CcoICgY3yVDk2u1LQUCMHbAj0fjlxIX+873psXlIKNA=
github.com/swaggo/swag v1.7.9/go.mod h1:gZ+TJ2w/Ve1RwQsA2IRoSOTidHz6DX+PIG8GWvbnoLU=
github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe h1:K8pHPVoTgxFJt1lXuIzzOX7zZhZFldJQK/CgKx9BFIc=
github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w=
github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI=
github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
Expand Down Expand Up @@ -101,7 +98,6 @@ golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuX
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
Expand Down
7 changes: 7 additions & 0 deletions example/go-chi/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,15 @@ func main() {
r := chi.NewRouter()

r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.ScriptSrc("https://unpkg.com/htm@3.1.1/dist/htm.js"),
httpSwagger.ScriptSrc("https://unpkg.com/react@17.0.2/umd/react.production.min.js"),
httpSwagger.ScriptSrc("/static/myplugin.js"),
httpSwagger.Plugins([]string{"MyPlugin"}),
httpSwagger.URL("http://localhost:1323/swagger/doc.json"), //The url pointing to API definition
))

fs := http.FileServer(http.Dir("static"))
r.Handle("/static/*", http.StripPrefix("/static/", fs))

log.Fatal(http.ListenAndServe(":1323", r))
}
80 changes: 80 additions & 0 deletions example/go-chi/static/myplugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Swagger UI Version: 4.15.5

'use strict';

function _typeof(obj) {
if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj &&
typeof Symbol === 'function' &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? 'symbol'
: typeof obj;
};
}
return _typeof(obj);
}

// From: https://raw.githubusercontent.com/chilts/umd-template/master/template.js
(function (f) {
// module name and requires
var name = 'MyPlugin';
var requires = []; // CommonJS

if (
(typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' &&
typeof module !== 'undefined'
) {
module.exports = f.apply(
null,
requires.map(function (r) {
return require(r);
})
); // RequireJS
} else if (typeof define === 'function' && define.amd) {
define(requires, f); // <script>
} else {
var g;

if (typeof window !== 'undefined') {
g = window;
} else if (typeof global !== 'undefined') {
g = global;
} else if (typeof self !== 'undefined') {
g = self;
} else {
// works providing we're not in "use strict";
// needed for Java 8 Nashorn
// seee https://github.com/facebook/react/issues/3037
g = this;
}

g[name] = f.apply(
null,
requires.map(function (r) {
return g[r];
})
);
}
})(function () {
return function (system) {
return {
wrapComponents: {
info: (Original, system) => (props) => {
const html = htm.bind(React.createElement);
// Uses https://github.com/developit/htm to render JSX.
return html`
<div>
<h3>Hello world! I am above the Info component.</h3>
<Original {...props} />
</div>`;
}
},
};
};
});
11 changes: 11 additions & 0 deletions swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type Config struct {
BeforeScript template.JS
AfterScript template.JS
Plugins []template.JS
ScriptSrcs []string // URLs to the extra scripts to load
UIConfig map[template.JS]template.JS
DeepLinking bool
PersistAuthorization bool
Expand Down Expand Up @@ -84,6 +85,13 @@ func Plugins(plugins []string) func(*Config) {
}
}

// Adds `<script src="src"></script>`
func ScriptSrc(src string) func(*Config) {
return func(c *Config) {
c.ScriptSrcs = append(c.ScriptSrcs, src)
}
}

// UIConfig specifies additional SwaggerUIBundle config object properties.
func UIConfig(props map[string]string) func(*Config) {
return func(c *Config) {
Expand Down Expand Up @@ -259,6 +267,9 @@ const indexTempl = `<!-- HTML for static distribution bundle build -->
<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
{{- range $script := .ScriptSrcs }}
<script src="{{$script}}"> </script>
{{- end}}
<script>
window.onload = function() {
{{- if .BeforeScript}}
Expand Down
11 changes: 11 additions & 0 deletions swagger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,13 @@ func TestConfigURL(t *testing.T) {
// Some plugin
});`),
},
{
desc: "configure ScriptSrcs",
exp: &Config{
ScriptSrcs: []string{`/scripts/helper.js`},
},
cfgfn: ScriptSrc(`/scripts/helper.js`),
},
}

for _, fix := range fixtures {
Expand Down Expand Up @@ -318,6 +325,8 @@ func TestUIConfigOptions(t *testing.T) {
<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
<script src="./a.js"> </script>
<script src="./b.js"> </script>
<script>
`
ftr := `
Expand All @@ -336,6 +345,7 @@ func TestUIConfigOptions(t *testing.T) {
DocExpansion: "list",
DomID: "swagger-ui",
PersistAuthorization: false,
ScriptSrcs: []string{"./a.js", "./b.js"},
},
exp: `window.onload = function() {
Expand Down Expand Up @@ -379,6 +389,7 @@ func TestUIConfigOptions(t *testing.T) {
"SomePlugin",
"AnotherPlugin",
},
ScriptSrcs: []string{"./a.js", "./b.js"},
UIConfig: map[template.JS]template.JS{
"showExtensions": "true",
"onComplete": `() => { window.ui.setBasePath('v3'); }`,
Expand Down

0 comments on commit 39c92d8

Please sign in to comment.