diff options
Diffstat (limited to 'vendor/github.com/gin-contrib')
31 files changed, 0 insertions, 2496 deletions
diff --git a/vendor/github.com/gin-contrib/cors/.gitignore b/vendor/github.com/gin-contrib/cors/.gitignore deleted file mode 100644 index 002df848c..000000000 --- a/vendor/github.com/gin-contrib/cors/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -*.o -*.a -*.so - -_obj -_test - -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -coverage.out - -.idea diff --git a/vendor/github.com/gin-contrib/cors/.golangci.yml b/vendor/github.com/gin-contrib/cors/.golangci.yml deleted file mode 100644 index d59c99bd4..000000000 --- a/vendor/github.com/gin-contrib/cors/.golangci.yml +++ /dev/null @@ -1,39 +0,0 @@ -linters: - enable-all: false - disable-all: true - fast: false - enable: - - bodyclose - - dogsled - - dupl - - errcheck - - exportloopref - - exhaustive - - gochecknoinits - - goconst - - gocritic - - gocyclo - - gofmt - - goimports - - goprintffuncname - - gosec - - gosimple - - govet - - ineffassign - - lll - - misspell - - nakedret - - noctx - - nolintlint - - rowserrcheck - - staticcheck - - stylecheck - - typecheck - - unconvert - - unparam - - unused - - whitespace - - gofumpt - -run: - timeout: 3m diff --git a/vendor/github.com/gin-contrib/cors/.goreleaser.yaml b/vendor/github.com/gin-contrib/cors/.goreleaser.yaml deleted file mode 100644 index 01b1081cf..000000000 --- a/vendor/github.com/gin-contrib/cors/.goreleaser.yaml +++ /dev/null @@ -1,28 +0,0 @@ -builds: - - # If true, skip the build. - # Useful for library projects. - # Default is false - skip: true - -changelog: - use: github - groups: - - title: Features - regexp: "^.*feat[(\\w)]*:+.*$" - order: 0 - - title: "Bug fixes" - regexp: "^.*fix[(\\w)]*:+.*$" - order: 1 - - title: "Enhancements" - regexp: "^.*chore[(\\w)]*:+.*$" - order: 2 - - title: "Refactor" - regexp: "^.*refactor[(\\w)]*:+.*$" - order: 3 - - title: "Build process updates" - regexp: ^.*?(build|ci)(\(.+\))??!?:.+$ - order: 4 - - title: "Documentation updates" - regexp: ^.*?docs?(\(.+\))??!?:.+$ - order: 4 - - title: Others diff --git a/vendor/github.com/gin-contrib/cors/LICENSE b/vendor/github.com/gin-contrib/cors/LICENSE deleted file mode 100644 index 4e2cfb015..000000000 --- a/vendor/github.com/gin-contrib/cors/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Gin-Gonic - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/gin-contrib/cors/README.md b/vendor/github.com/gin-contrib/cors/README.md deleted file mode 100644 index d43523295..000000000 --- a/vendor/github.com/gin-contrib/cors/README.md +++ /dev/null @@ -1,95 +0,0 @@ -# CORS gin's middleware - -[](https://github.com/gin-contrib/cors/actions/workflows/go.yml) -[](https://codecov.io/gh/gin-contrib/cors) -[](https://goreportcard.com/report/github.com/gin-contrib/cors) -[](https://godoc.org/github.com/gin-contrib/cors) - -Gin middleware/handler to enable CORS support. - -## Usage - -### Start using it - -Download and install it: - -```sh -go get github.com/gin-contrib/cors -``` - -Import it in your code: - -```go -import "github.com/gin-contrib/cors" -``` - -### Canonical example - -```go -package main - -import ( - "time" - - "github.com/gin-contrib/cors" - "github.com/gin-gonic/gin" -) - -func main() { - router := gin.Default() - // CORS for https://foo.com and https://github.com origins, allowing: - // - PUT and PATCH methods - // - Origin header - // - Credentials share - // - Preflight requests cached for 12 hours - router.Use(cors.New(cors.Config{ - AllowOrigins: []string{"https://foo.com"}, - AllowMethods: []string{"PUT", "PATCH"}, - AllowHeaders: []string{"Origin"}, - ExposeHeaders: []string{"Content-Length"}, - AllowCredentials: true, - AllowOriginFunc: func(origin string) bool { - return origin == "https://github.com" - }, - MaxAge: 12 * time.Hour, - })) - router.Run() -} -``` - -### Using DefaultConfig as start point - -```go -func main() { - router := gin.Default() - // - No origin allowed by default - // - GET,POST, PUT, HEAD methods - // - Credentials share disabled - // - Preflight requests cached for 12 hours - config := cors.DefaultConfig() - config.AllowOrigins = []string{"http://google.com"} - // config.AllowOrigins = []string{"http://google.com", "http://facebook.com"} - // config.AllowAllOrigins = true - - router.Use(cors.New(config)) - router.Run() -} -``` - -Note: while Default() allows all origins, DefaultConfig() does not and you will still have to use AllowAllOrigins. - -### Default() allows all origins - -```go -func main() { - router := gin.Default() - // same as - // config := cors.DefaultConfig() - // config.AllowAllOrigins = true - // router.Use(cors.New(config)) - router.Use(cors.Default()) - router.Run() -} -``` - -Using all origins disables the ability for Gin to set cookies for clients. When dealing with credentials, don't allow all origins. diff --git a/vendor/github.com/gin-contrib/cors/config.go b/vendor/github.com/gin-contrib/cors/config.go deleted file mode 100644 index 8a295e3db..000000000 --- a/vendor/github.com/gin-contrib/cors/config.go +++ /dev/null @@ -1,155 +0,0 @@ -package cors - -import ( - "net/http" - "strings" - - "github.com/gin-gonic/gin" -) - -type cors struct { - allowAllOrigins bool - allowCredentials bool - allowOriginFunc func(string) bool - allowOriginWithContextFunc func(*gin.Context, string) bool - allowOrigins []string - normalHeaders http.Header - preflightHeaders http.Header - wildcardOrigins [][]string - optionsResponseStatusCode int -} - -var ( - DefaultSchemas = []string{ - "http://", - "https://", - } - ExtensionSchemas = []string{ - "chrome-extension://", - "safari-extension://", - "moz-extension://", - "ms-browser-extension://", - } - FileSchemas = []string{ - "file://", - } - WebSocketSchemas = []string{ - "ws://", - "wss://", - } -) - -func newCors(config Config) *cors { - if err := config.Validate(); err != nil { - panic(err.Error()) - } - - for _, origin := range config.AllowOrigins { - if origin == "*" { - config.AllowAllOrigins = true - } - } - - if config.OptionsResponseStatusCode == 0 { - config.OptionsResponseStatusCode = http.StatusNoContent - } - - return &cors{ - allowOriginFunc: config.AllowOriginFunc, - allowOriginWithContextFunc: config.AllowOriginWithContextFunc, - allowAllOrigins: config.AllowAllOrigins, - allowCredentials: config.AllowCredentials, - allowOrigins: normalize(config.AllowOrigins), - normalHeaders: generateNormalHeaders(config), - preflightHeaders: generatePreflightHeaders(config), - wildcardOrigins: config.parseWildcardRules(), - optionsResponseStatusCode: config.OptionsResponseStatusCode, - } -} - -func (cors *cors) applyCors(c *gin.Context) { - origin := c.Request.Header.Get("Origin") - if len(origin) == 0 { - // request is not a CORS request - return - } - host := c.Request.Host - - if origin == "http://"+host || origin == "https://"+host { - // request is not a CORS request but have origin header. - // for example, use fetch api - return - } - - if !cors.isOriginValid(c, origin) { - c.AbortWithStatus(http.StatusForbidden) - return - } - - if c.Request.Method == "OPTIONS" { - cors.handlePreflight(c) - defer c.AbortWithStatus(cors.optionsResponseStatusCode) - } else { - cors.handleNormal(c) - } - - if !cors.allowAllOrigins { - c.Header("Access-Control-Allow-Origin", origin) - } -} - -func (cors *cors) validateWildcardOrigin(origin string) bool { - for _, w := range cors.wildcardOrigins { - if w[0] == "*" && strings.HasSuffix(origin, w[1]) { - return true - } - if w[1] == "*" && strings.HasPrefix(origin, w[0]) { - return true - } - if strings.HasPrefix(origin, w[0]) && strings.HasSuffix(origin, w[1]) { - return true - } - } - - return false -} - -func (cors *cors) isOriginValid(c *gin.Context, origin string) bool { - valid := cors.validateOrigin(origin) - if !valid && cors.allowOriginWithContextFunc != nil { - valid = cors.allowOriginWithContextFunc(c, origin) - } - return valid -} - -func (cors *cors) validateOrigin(origin string) bool { - if cors.allowAllOrigins { - return true - } - for _, value := range cors.allowOrigins { - if value == origin { - return true - } - } - if len(cors.wildcardOrigins) > 0 && cors.validateWildcardOrigin(origin) { - return true - } - if cors.allowOriginFunc != nil { - return cors.allowOriginFunc(origin) - } - return false -} - -func (cors *cors) handlePreflight(c *gin.Context) { - header := c.Writer.Header() - for key, value := range cors.preflightHeaders { - header[key] = value - } -} - -func (cors *cors) handleNormal(c *gin.Context) { - header := c.Writer.Header() - for key, value := range cors.normalHeaders { - header[key] = value - } -} diff --git a/vendor/github.com/gin-contrib/cors/cors.go b/vendor/github.com/gin-contrib/cors/cors.go deleted file mode 100644 index 2261df759..000000000 --- a/vendor/github.com/gin-contrib/cors/cors.go +++ /dev/null @@ -1,198 +0,0 @@ -package cors - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/gin-gonic/gin" -) - -// Config represents all available options for the middleware. -type Config struct { - AllowAllOrigins bool - - // AllowOrigins is a list of origins a cross-domain request can be executed from. - // If the special "*" value is present in the list, all origins will be allowed. - // Default value is [] - AllowOrigins []string - - // AllowOriginFunc is a custom function to validate the origin. It takes the origin - // as an argument and returns true if allowed or false otherwise. If this option is - // set, the content of AllowOrigins is ignored. - AllowOriginFunc func(origin string) bool - - // Same as AllowOriginFunc except also receives the full request context. - // This function should use the context as a read only source and not - // have any side effects on the request, such as aborting or injecting - // values on the request. - AllowOriginWithContextFunc func(c *gin.Context, origin string) bool - - // AllowMethods is a list of methods the client is allowed to use with - // cross-domain requests. Default value is simple methods (GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS) - AllowMethods []string - - // AllowPrivateNetwork indicates whether the response should include allow private network header - AllowPrivateNetwork bool - - // AllowHeaders is list of non simple headers the client is allowed to use with - // cross-domain requests. - AllowHeaders []string - - // AllowCredentials indicates whether the request can include user credentials like - // cookies, HTTP authentication or client side SSL certificates. - AllowCredentials bool - - // ExposeHeaders indicates which headers are safe to expose to the API of a CORS - // API specification - ExposeHeaders []string - - // MaxAge indicates how long (with second-precision) the results of a preflight request - // can be cached - MaxAge time.Duration - - // Allows to add origins like http://some-domain/*, https://api.* or http://some.*.subdomain.com - AllowWildcard bool - - // Allows usage of popular browser extensions schemas - AllowBrowserExtensions bool - - // Allows to add custom schema like tauri:// - CustomSchemas []string - - // Allows usage of WebSocket protocol - AllowWebSockets bool - - // Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed - AllowFiles bool - - // Allows to pass custom OPTIONS response status code for old browsers / clients - OptionsResponseStatusCode int -} - -// AddAllowMethods is allowed to add custom methods -func (c *Config) AddAllowMethods(methods ...string) { - c.AllowMethods = append(c.AllowMethods, methods...) -} - -// AddAllowHeaders is allowed to add custom headers -func (c *Config) AddAllowHeaders(headers ...string) { - c.AllowHeaders = append(c.AllowHeaders, headers...) -} - -// AddExposeHeaders is allowed to add custom expose headers -func (c *Config) AddExposeHeaders(headers ...string) { - c.ExposeHeaders = append(c.ExposeHeaders, headers...) -} - -func (c Config) getAllowedSchemas() []string { - allowedSchemas := DefaultSchemas - if c.AllowBrowserExtensions { - allowedSchemas = append(allowedSchemas, ExtensionSchemas...) - } - if c.AllowWebSockets { - allowedSchemas = append(allowedSchemas, WebSocketSchemas...) - } - if c.AllowFiles { - allowedSchemas = append(allowedSchemas, FileSchemas...) - } - if c.CustomSchemas != nil { - allowedSchemas = append(allowedSchemas, c.CustomSchemas...) - } - return allowedSchemas -} - -func (c Config) validateAllowedSchemas(origin string) bool { - allowedSchemas := c.getAllowedSchemas() - for _, schema := range allowedSchemas { - if strings.HasPrefix(origin, schema) { - return true - } - } - return false -} - -// Validate is check configuration of user defined. -func (c Config) Validate() error { - hasOriginFn := c.AllowOriginFunc != nil - hasOriginFn = hasOriginFn || c.AllowOriginWithContextFunc != nil - - if c.AllowAllOrigins && (hasOriginFn || len(c.AllowOrigins) > 0) { - originFields := strings.Join([]string{ - "AllowOriginFunc", - "AllowOriginFuncWithContext", - "AllowOrigins", - }, " or ") - return fmt.Errorf( - "conflict settings: all origins enabled. %s is not needed", - originFields, - ) - } - if !c.AllowAllOrigins && !hasOriginFn && len(c.AllowOrigins) == 0 { - return errors.New("conflict settings: all origins disabled") - } - for _, origin := range c.AllowOrigins { - if !strings.Contains(origin, "*") && !c.validateAllowedSchemas(origin) { - return errors.New("bad origin: origins must contain '*' or include " + strings.Join(c.getAllowedSchemas(), ",")) - } - } - return nil -} - -func (c Config) parseWildcardRules() [][]string { - var wRules [][]string - - if !c.AllowWildcard { - return wRules - } - - for _, o := range c.AllowOrigins { - if !strings.Contains(o, "*") { - continue - } - - if c := strings.Count(o, "*"); c > 1 { - panic(errors.New("only one * is allowed").Error()) - } - - i := strings.Index(o, "*") - if i == 0 { - wRules = append(wRules, []string{"*", o[1:]}) - continue - } - if i == (len(o) - 1) { - wRules = append(wRules, []string{o[:i], "*"}) - continue - } - - wRules = append(wRules, []string{o[:i], o[i+1:]}) - } - - return wRules -} - -// DefaultConfig returns a generic default configuration mapped to localhost. -func DefaultConfig() Config { - return Config{ - AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}, - AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"}, - AllowCredentials: false, - MaxAge: 12 * time.Hour, - } -} - -// Default returns the location middleware with default configuration. -func Default() gin.HandlerFunc { - config := DefaultConfig() - config.AllowAllOrigins = true - return New(config) -} - -// New returns the location middleware with user-defined custom configuration. -func New(config Config) gin.HandlerFunc { - cors := newCors(config) - return func(c *gin.Context) { - cors.applyCors(c) - } -} diff --git a/vendor/github.com/gin-contrib/cors/utils.go b/vendor/github.com/gin-contrib/cors/utils.go deleted file mode 100644 index b98e90b8c..000000000 --- a/vendor/github.com/gin-contrib/cors/utils.go +++ /dev/null @@ -1,90 +0,0 @@ -package cors - -import ( - "net/http" - "strconv" - "strings" - "time" -) - -type converter func(string) string - -func generateNormalHeaders(c Config) http.Header { - headers := make(http.Header) - if c.AllowCredentials { - headers.Set("Access-Control-Allow-Credentials", "true") - } - if len(c.ExposeHeaders) > 0 { - exposeHeaders := convert(normalize(c.ExposeHeaders), http.CanonicalHeaderKey) - headers.Set("Access-Control-Expose-Headers", strings.Join(exposeHeaders, ",")) - } - if c.AllowAllOrigins { - headers.Set("Access-Control-Allow-Origin", "*") - } else { - headers.Set("Vary", "Origin") - } - return headers -} - -func generatePreflightHeaders(c Config) http.Header { - headers := make(http.Header) - if c.AllowCredentials { - headers.Set("Access-Control-Allow-Credentials", "true") - } - if len(c.AllowMethods) > 0 { - allowMethods := convert(normalize(c.AllowMethods), strings.ToUpper) - value := strings.Join(allowMethods, ",") - headers.Set("Access-Control-Allow-Methods", value) - } - if len(c.AllowHeaders) > 0 { - allowHeaders := convert(normalize(c.AllowHeaders), http.CanonicalHeaderKey) - value := strings.Join(allowHeaders, ",") - headers.Set("Access-Control-Allow-Headers", value) - } - if c.MaxAge > time.Duration(0) { - value := strconv.FormatInt(int64(c.MaxAge/time.Second), 10) - headers.Set("Access-Control-Max-Age", value) - } - - if c.AllowPrivateNetwork { - headers.Set("Access-Control-Allow-Private-Network", "true") - } - - if c.AllowAllOrigins { - headers.Set("Access-Control-Allow-Origin", "*") - } else { - // Always set Vary headers - // see https://github.com/rs/cors/issues/10, - // https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001 - - headers.Add("Vary", "Origin") - headers.Add("Vary", "Access-Control-Request-Method") - headers.Add("Vary", "Access-Control-Request-Headers") - } - return headers -} - -func normalize(values []string) []string { - if values == nil { - return nil - } - distinctMap := make(map[string]bool, len(values)) - normalized := make([]string, 0, len(values)) - for _, value := range values { - value = strings.TrimSpace(value) - value = strings.ToLower(value) - if _, seen := distinctMap[value]; !seen { - normalized = append(normalized, value) - distinctMap[value] = true - } - } - return normalized -} - -func convert(s []string, c converter) []string { - var out []string - for _, i := range s { - out = append(out, c(i)) - } - return out -} diff --git a/vendor/github.com/gin-contrib/gzip/.gitignore b/vendor/github.com/gin-contrib/gzip/.gitignore deleted file mode 100644 index 2d830686d..000000000 --- a/vendor/github.com/gin-contrib/gzip/.gitignore +++ /dev/null @@ -1 +0,0 @@ -coverage.out diff --git a/vendor/github.com/gin-contrib/gzip/.golangci.yml b/vendor/github.com/gin-contrib/gzip/.golangci.yml deleted file mode 100644 index d5cbd0a39..000000000 --- a/vendor/github.com/gin-contrib/gzip/.golangci.yml +++ /dev/null @@ -1,38 +0,0 @@ -linters: - enable-all: false - disable-all: true - fast: false - enable: - - bodyclose - - dogsled - - dupl - - errcheck - - exportloopref - - exhaustive - - gochecknoinits - - goconst - - gocritic - - gocyclo - - gofmt - - goimports - - goprintffuncname - - gosec - - gosimple - - govet - - ineffassign - - lll - - misspell - - nakedret - - noctx - - nolintlint - - rowserrcheck - - staticcheck - - stylecheck - - typecheck - - unconvert - - unparam - - unused - - whitespace - - gofumpt -run: - timeout: 3m diff --git a/vendor/github.com/gin-contrib/gzip/.goreleaser.yaml b/vendor/github.com/gin-contrib/gzip/.goreleaser.yaml deleted file mode 100644 index 4c910add4..000000000 --- a/vendor/github.com/gin-contrib/gzip/.goreleaser.yaml +++ /dev/null @@ -1,29 +0,0 @@ -builds: - - # If true, skip the build. - # Useful for library projects. - # Default is false - skip: true - -changelog: - use: github - groups: - - title: Features - regexp: "^.*feat[(\\w)]*:+.*$" - order: 0 - - title: "Bug fixes" - regexp: "^.*fix[(\\w)]*:+.*$" - order: 1 - - title: "Enhancements" - regexp: "^.*chore[(\\w)]*:+.*$" - order: 2 - - title: "Refactor" - regexp: "^.*refactor[(\\w)]*:+.*$" - order: 3 - - title: "Build process updates" - regexp: ^.*?(build|ci)(\(.+\))??!?:.+$ - order: 4 - - title: "Documentation updates" - regexp: ^.*?docs?(\(.+\))??!?:.+$ - order: 4 - - title: Others - order: 999 diff --git a/vendor/github.com/gin-contrib/gzip/LICENSE b/vendor/github.com/gin-contrib/gzip/LICENSE deleted file mode 100644 index a863f57ca..000000000 --- a/vendor/github.com/gin-contrib/gzip/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Gin-Gonic - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/gin-contrib/gzip/README.md b/vendor/github.com/gin-contrib/gzip/README.md deleted file mode 100644 index bb651977c..000000000 --- a/vendor/github.com/gin-contrib/gzip/README.md +++ /dev/null @@ -1,169 +0,0 @@ -# GZIP gin's middleware - -[](https://github.com/gin-contrib/gzip/actions/workflows/go.yml) -[](https://codecov.io/gh/gin-contrib/gzip) -[](https://goreportcard.com/report/github.com/gin-contrib/gzip) -[](https://godoc.org/github.com/gin-contrib/gzip) - -Gin middleware to enable `GZIP` support. - -## Usage - -Download and install it: - -```sh -go get github.com/gin-contrib/gzip -``` - -Import it in your code: - -```go -import "github.com/gin-contrib/gzip" -``` - -Canonical example: - -```go -package main - -import ( - "fmt" - "net/http" - "time" - - "github.com/gin-contrib/gzip" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - r.Use(gzip.Gzip(gzip.DefaultCompression)) - r.GET("/ping", func(c *gin.Context) { - c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix())) - }) - - // Listen and Server in 0.0.0.0:8080 - if err := r.Run(":8080"); err != nil { - log.Fatal(err) - } -} -``` - -### Customized Excluded Extensions - -```go -package main - -import ( - "fmt" - "net/http" - "time" - - "github.com/gin-contrib/gzip" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedExtensions([]string{".pdf", ".mp4"}))) - r.GET("/ping", func(c *gin.Context) { - c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix())) - }) - - // Listen and Server in 0.0.0.0:8080 - if err := r.Run(":8080"); err != nil { - log.Fatal(err) - } -} -``` - -### Customized Excluded Paths - -```go -package main - -import ( - "fmt" - "net/http" - "time" - - "github.com/gin-contrib/gzip" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{"/api/"}))) - r.GET("/ping", func(c *gin.Context) { - c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix())) - }) - - // Listen and Server in 0.0.0.0:8080 - if err := r.Run(":8080"); err != nil { - log.Fatal(err) - } -} -``` - -### Customized Excluded Paths with Regex - -```go -package main - -import ( - "fmt" - "net/http" - "time" - - "github.com/gin-contrib/gzip" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPathsRegexs([]string{".*"}))) - r.GET("/ping", func(c *gin.Context) { - c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix())) - }) - - // Listen and Server in 0.0.0.0:8080 - if err := r.Run(":8080"); err != nil { - log.Fatal(err) - } -} -``` - -### Server Push - -```go -package main - -import ( - "fmt" - "log" - "net/http" - "time" - - "github.com/gin-contrib/gzip" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - r.Use(gzip.Gzip(gzip.DefaultCompression)) - r.GET("/stream", func(c *gin.Context) { - c.Header("Content-Type", "text/event-stream") - c.Header("Connection", "keep-alive") - for i := 0; i < 10; i++ { - fmt.Fprintf(c.Writer, "id: %d\ndata: tick %d\n\n", i, time.Now().Unix()) - c.Writer.Flush() - time.Sleep(1 * time.Second) - } - }) - - // Listen and Server in 0.0.0.0:8080 - if err := r.Run(":8080"); err != nil { - log.Fatal(err) - } -} -``` diff --git a/vendor/github.com/gin-contrib/gzip/gzip.go b/vendor/github.com/gin-contrib/gzip/gzip.go deleted file mode 100644 index 931945a88..000000000 --- a/vendor/github.com/gin-contrib/gzip/gzip.go +++ /dev/null @@ -1,67 +0,0 @@ -package gzip - -import ( - "bufio" - "compress/gzip" - "errors" - "net" - "net/http" - - "github.com/gin-gonic/gin" -) - -const ( - BestCompression = gzip.BestCompression - BestSpeed = gzip.BestSpeed - DefaultCompression = gzip.DefaultCompression - NoCompression = gzip.NoCompression - HuffmanOnly = gzip.HuffmanOnly -) - -func Gzip(level int, options ...Option) gin.HandlerFunc { - return newGzipHandler(level, options...).Handle -} - -type gzipWriter struct { - gin.ResponseWriter - writer *gzip.Writer -} - -func (g *gzipWriter) WriteString(s string) (int, error) { - g.Header().Del("Content-Length") - return g.writer.Write([]byte(s)) -} - -func (g *gzipWriter) Write(data []byte) (int, error) { - g.Header().Del("Content-Length") - return g.writer.Write(data) -} - -func (g *gzipWriter) Flush() { - _ = g.writer.Flush() - g.ResponseWriter.Flush() -} - -// Fix: https://github.com/mholt/caddy/issues/38 -func (g *gzipWriter) WriteHeader(code int) { - g.Header().Del("Content-Length") - g.ResponseWriter.WriteHeader(code) -} - -// Ensure gzipWriter implements the http.Hijacker interface. -// This will cause a compile-time error if gzipWriter does not implement all methods of the http.Hijacker interface. -var _ http.Hijacker = (*gzipWriter)(nil) - -// Hijack allows the caller to take over the connection from the HTTP server. -// After a call to Hijack, the HTTP server library will not do anything else with the connection. -// It becomes the caller's responsibility to manage and close the connection. -// -// It returns the underlying net.Conn, a buffered reader/writer for the connection, and an error -// if the ResponseWriter does not support the Hijacker interface. -func (g *gzipWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - hijacker, ok := g.ResponseWriter.(http.Hijacker) - if !ok { - return nil, nil, errors.New("the ResponseWriter doesn't support the Hijacker interface") - } - return hijacker.Hijack() -} diff --git a/vendor/github.com/gin-contrib/gzip/handler.go b/vendor/github.com/gin-contrib/gzip/handler.go deleted file mode 100644 index 412c8386b..000000000 --- a/vendor/github.com/gin-contrib/gzip/handler.go +++ /dev/null @@ -1,117 +0,0 @@ -package gzip - -import ( - "compress/gzip" - "io" - "net/http" - "path/filepath" - "strconv" - "strings" - "sync" - - "github.com/gin-gonic/gin" -) - -const ( - headerAcceptEncoding = "Accept-Encoding" - headerContentEncoding = "Content-Encoding" - headerVary = "Vary" -) - -type gzipHandler struct { - *config - gzPool sync.Pool -} - -func isCompressionLevelValid(level int) bool { - return level == gzip.DefaultCompression || - level == gzip.NoCompression || - (level >= gzip.BestSpeed && level <= gzip.BestCompression) -} - -func newGzipHandler(level int, opts ...Option) *gzipHandler { - cfg := &config{ - excludedExtensions: DefaultExcludedExtentions, - } - - // Apply each option to the config - for _, o := range opts { - o.apply(cfg) - } - - if !isCompressionLevelValid(level) { - // For web content, level 4 seems to be a sweet spot. - level = 4 - } - - handler := &gzipHandler{ - config: cfg, - gzPool: sync.Pool{ - New: func() interface{} { - gz, _ := gzip.NewWriterLevel(io.Discard, level) - return gz - }, - }, - } - return handler -} - -// Handle is a middleware function for handling gzip compression in HTTP requests and responses. -// It first checks if the request has a "Content-Encoding" header set to "gzip" and if a decompression -// function is provided, it will call the decompression function. If the handler is set to decompress only, -// or if the custom compression decision function indicates not to compress, it will return early. -// Otherwise, it retrieves a gzip.Writer from the pool, sets the necessary response headers for gzip encoding, -// and wraps the response writer with a gzipWriter. After the request is processed, it ensures the gzip.Writer -// is properly closed and the "Content-Length" header is set based on the response size. -func (g *gzipHandler) Handle(c *gin.Context) { - if fn := g.decompressFn; fn != nil && strings.Contains(c.Request.Header.Get("Content-Encoding"), "gzip") { - fn(c) - } - - if g.decompressOnly || - (g.customShouldCompressFn != nil && !g.customShouldCompressFn(c)) || - (g.customShouldCompressFn == nil && !g.shouldCompress(c.Request)) { - return - } - - gz := g.gzPool.Get().(*gzip.Writer) - gz.Reset(c.Writer) - - c.Header(headerContentEncoding, "gzip") - c.Writer.Header().Add(headerVary, headerAcceptEncoding) - // check ETag Header - originalEtag := c.GetHeader("ETag") - if originalEtag != "" && !strings.HasPrefix(originalEtag, "W/") { - c.Header("ETag", "W/"+originalEtag) - } - c.Writer = &gzipWriter{c.Writer, gz} - defer func() { - if c.Writer.Size() < 0 { - // do not write gzip footer when nothing is written to the response body - gz.Reset(io.Discard) - } - _ = gz.Close() - if c.Writer.Size() > -1 { - c.Header("Content-Length", strconv.Itoa(c.Writer.Size())) - } - g.gzPool.Put(gz) - }() - c.Next() -} - -func (g *gzipHandler) shouldCompress(req *http.Request) bool { - if !strings.Contains(req.Header.Get(headerAcceptEncoding), "gzip") || - strings.Contains(req.Header.Get("Connection"), "Upgrade") { - return false - } - - // Check if the request path is excluded from compression - extension := filepath.Ext(req.URL.Path) - if g.excludedExtensions.Contains(extension) || - g.excludedPaths.Contains(req.URL.Path) || - g.excludedPathesRegexs.Contains(req.URL.Path) { - return false - } - - return true -} diff --git a/vendor/github.com/gin-contrib/gzip/options.go b/vendor/github.com/gin-contrib/gzip/options.go deleted file mode 100644 index 67607f51b..000000000 --- a/vendor/github.com/gin-contrib/gzip/options.go +++ /dev/null @@ -1,270 +0,0 @@ -package gzip - -import ( - "compress/gzip" - "errors" - "io" - "net/http" - "regexp" - "strings" - - "github.com/gin-gonic/gin" -) - -var ( - // DefaultExcludedExtentions is a predefined list of file extensions that should be excluded from gzip compression. - // These extensions typically represent image files that are already compressed - // and do not benefit from additional compression. - DefaultExcludedExtentions = NewExcludedExtensions([]string{ - ".png", ".gif", ".jpeg", ".jpg", - }) - // ErrUnsupportedContentEncoding is an error that indicates the content encoding - // is not supported by the application. - ErrUnsupportedContentEncoding = errors.New("unsupported content encoding") -) - -// Option is an interface that defines a method to apply a configuration -// to a given config instance. Implementations of this interface can be -// used to modify the configuration settings of the logger. -type Option interface { - apply(*config) -} - -// Ensures that optionFunc implements the Option interface at compile time. -// If optionFunc does not implement Option, a compile-time error will occur. -var _ Option = (*optionFunc)(nil) - -type optionFunc func(*config) - -func (o optionFunc) apply(c *config) { - o(c) -} - -type config struct { - excludedExtensions ExcludedExtensions - excludedPaths ExcludedPaths - excludedPathesRegexs ExcludedPathesRegexs - decompressFn func(c *gin.Context) - decompressOnly bool - customShouldCompressFn func(c *gin.Context) bool -} - -// WithExcludedExtensions returns an Option that sets the ExcludedExtensions field of the Options struct. -// Parameters: -// - args: []string - A slice of file extensions to exclude from gzip compression. -func WithExcludedExtensions(args []string) Option { - return optionFunc(func(o *config) { - o.excludedExtensions = NewExcludedExtensions(args) - }) -} - -// WithExcludedPaths returns an Option that sets the ExcludedPaths field of the Options struct. -// Parameters: -// - args: []string - A slice of paths to exclude from gzip compression. -func WithExcludedPaths(args []string) Option { - return optionFunc(func(o *config) { - o.excludedPaths = NewExcludedPaths(args) - }) -} - -// WithExcludedPathsRegexs returns an Option that sets the ExcludedPathesRegexs field of the Options struct. -// Parameters: -// - args: []string - A slice of regex patterns to exclude paths from gzip compression. -func WithExcludedPathsRegexs(args []string) Option { - return optionFunc(func(o *config) { - o.excludedPathesRegexs = NewExcludedPathesRegexs(args) - }) -} - -// WithDecompressFn returns an Option that sets the DecompressFn field of the Options struct. -// Parameters: -// - decompressFn: func(c *gin.Context) - A function to handle decompression of incoming requests. -func WithDecompressFn(decompressFn func(c *gin.Context)) Option { - return optionFunc(func(o *config) { - o.decompressFn = decompressFn - }) -} - -// WithDecompressOnly is an option that configures the gzip middleware to only -// decompress incoming requests without compressing the responses. When this -// option is enabled, the middleware will set the DecompressOnly field of the -// Options struct to true. -func WithDecompressOnly() Option { - return optionFunc(func(o *config) { - o.decompressOnly = true - }) -} - -// WithCustomShouldCompressFn returns an Option that sets the CustomShouldCompressFn field of the Options struct. -// Parameters: -// - fn: func(c *gin.Context) bool - A function to determine if a request should be compressed. -// The function should return true if the request should be compressed, false otherwise. -// If the function returns false, the middleware will not compress the response. -// If the function is nil, the middleware will use the default logic to determine -// if the response should be compressed. -// -// Returns: -// - Option - An option that sets the CustomShouldCompressFn field of the Options struct. -// -// Example: -// -// router.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithCustomShouldCompressFn(func(c *gin.Context) bool { -// return c.Request.URL.Path != "/no-compress" -// }))) -func WithCustomShouldCompressFn(fn func(c *gin.Context) bool) Option { - return optionFunc(func(o *config) { - o.customShouldCompressFn = fn - }) -} - -// Using map for better lookup performance -type ExcludedExtensions map[string]struct{} - -// NewExcludedExtensions creates a new ExcludedExtensions map from a slice of file extensions. -// Parameters: -// - extensions: []string - A slice of file extensions to exclude from gzip compression. -// -// Returns: -// - ExcludedExtensions - A map of excluded file extensions. -func NewExcludedExtensions(extensions []string) ExcludedExtensions { - res := make(ExcludedExtensions, len(extensions)) - for _, e := range extensions { - res[e] = struct{}{} - } - return res -} - -// Contains checks if a given file extension is in the ExcludedExtensions map. -// Parameters: -// - target: string - The file extension to check. -// -// Returns: -// - bool - True if the extension is excluded, false otherwise. -func (e ExcludedExtensions) Contains(target string) bool { - _, ok := e[target] - return ok -} - -type ExcludedPaths []string - -// NewExcludedPaths creates a new ExcludedPaths slice from a slice of paths. -// Parameters: -// - paths: []string - A slice of paths to exclude from gzip compression. -// -// Returns: -// - ExcludedPaths - A slice of excluded paths. -func NewExcludedPaths(paths []string) ExcludedPaths { - return ExcludedPaths(paths) -} - -// Contains checks if a given request URI starts with any of the excluded paths. -// Parameters: -// - requestURI: string - The request URI to check. -// -// Returns: -// - bool - True if the URI starts with an excluded path, false otherwise. -func (e ExcludedPaths) Contains(requestURI string) bool { - for _, path := range e { - if strings.HasPrefix(requestURI, path) { - return true - } - } - return false -} - -type ExcludedPathesRegexs []*regexp.Regexp - -// NewExcludedPathesRegexs creates a new ExcludedPathesRegexs slice from a slice of regex patterns. -// Parameters: -// - regexs: []string - A slice of regex patterns to exclude paths from gzip compression. -// -// Returns: -// - ExcludedPathesRegexs - A slice of excluded path regex patterns. -func NewExcludedPathesRegexs(regexs []string) ExcludedPathesRegexs { - result := make(ExcludedPathesRegexs, len(regexs)) - for i, reg := range regexs { - result[i] = regexp.MustCompile(reg) - } - return result -} - -// Contains checks if a given request URI matches any of the excluded path regex patterns. -// Parameters: -// - requestURI: string - The request URI to check. -// -// Returns: -// - bool - True if the URI matches an excluded path regex pattern, false otherwise. -func (e ExcludedPathesRegexs) Contains(requestURI string) bool { - for _, reg := range e { - if reg.MatchString(requestURI) { - return true - } - } - return false -} - -// DefaultDecompressHandle is a middleware function for the Gin framework that -// decompresses the request body if it is gzip encoded. It checks if the request -// body is nil and returns immediately if it is. Otherwise, it attempts to create -// a new gzip reader from the request body. If an error occurs during this process, -// it aborts the request with a 400 Bad Request status and the error. If successful, -// it removes the "Content-Encoding" and "Content-Length" headers from the request -// and replaces the request body with the decompressed reader. -// -// Parameters: -// - c: *gin.Context - The Gin context for the current request. -func DefaultDecompressHandle(c *gin.Context) { - if c.Request.Body == nil { - return - } - - contentEncodingField := strings.Split(strings.ToLower(c.GetHeader("Content-Encoding")), ",") - if len(contentEncodingField) == 0 { // nothing to decompress - c.Next() - - return - } - - toClose := make([]io.Closer, 0, len(contentEncodingField)) - defer func() { - for i := len(toClose); i > 0; i-- { - toClose[i-1].Close() - } - }() - - // parses multiply gzips like - // Content-Encoding: gzip, gzip, gzip - // allowed by RFC - for i := 0; i < len(contentEncodingField); i++ { - trimmedValue := strings.TrimSpace(contentEncodingField[i]) - - if trimmedValue == "" { - continue - } - - if trimmedValue != "gzip" { - // According to RFC 7231, Section 3.1.2.2: - // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.2 - // An origin server MAY respond with a status code of 415 (Unsupported - // Media Type) if a representation in the request message has a content - // coding that is not acceptable. - _ = c.AbortWithError(http.StatusUnsupportedMediaType, ErrUnsupportedContentEncoding) - } - - r, err := gzip.NewReader(c.Request.Body) - if err != nil { - _ = c.AbortWithError(http.StatusBadRequest, err) - - return - } - - toClose = append(toClose, c.Request.Body) - - c.Request.Body = r - } - - c.Request.Header.Del("Content-Encoding") - c.Request.Header.Del("Content-Length") - - c.Next() -} diff --git a/vendor/github.com/gin-contrib/sessions/.gitignore b/vendor/github.com/gin-contrib/sessions/.gitignore deleted file mode 100644 index 18a5735c4..000000000 --- a/vendor/github.com/gin-contrib/sessions/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -coverage.out -vendor/* -!/vendor/vendor.json -/gorm/test.db -.idea diff --git a/vendor/github.com/gin-contrib/sessions/.goreleaser.yaml b/vendor/github.com/gin-contrib/sessions/.goreleaser.yaml deleted file mode 100644 index dc3a01fb7..000000000 --- a/vendor/github.com/gin-contrib/sessions/.goreleaser.yaml +++ /dev/null @@ -1,26 +0,0 @@ -builds: - - skip: true - -changelog: - use: github - groups: - - title: Features - regexp: "^.*feat[(\\w)]*:+.*$" - order: 0 - - title: "Bug fixes" - regexp: "^.*fix[(\\w)]*:+.*$" - order: 1 - - title: "Enhancements" - regexp: "^.*chore[(\\w)]*:+.*$" - order: 2 - - title: "Refactor" - regexp: "^.*refactor[(\\w)]*:+.*$" - order: 3 - - title: "Build process updates" - regexp: ^.*?(build|ci)(\(.+\))??!?:.+$ - order: 4 - - title: "Documentation updates" - regexp: ^.*?docs?(\(.+\))??!?:.+$ - order: 4 - - title: Others - order: 999 diff --git a/vendor/github.com/gin-contrib/sessions/LICENSE b/vendor/github.com/gin-contrib/sessions/LICENSE deleted file mode 100644 index 4e2cfb015..000000000 --- a/vendor/github.com/gin-contrib/sessions/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Gin-Gonic - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/gin-contrib/sessions/README.md b/vendor/github.com/gin-contrib/sessions/README.md deleted file mode 100644 index 86f4d0f9d..000000000 --- a/vendor/github.com/gin-contrib/sessions/README.md +++ /dev/null @@ -1,458 +0,0 @@ -# sessions - -[](https://github.com/gin-contrib/sessions/actions/workflows/lint.yml) -[](https://github.com/gin-contrib/sessions/actions/workflows/testing.yml) -[](https://codecov.io/gh/gin-contrib/sessions) -[](https://goreportcard.com/report/github.com/gin-contrib/sessions) -[](https://godoc.org/github.com/gin-contrib/sessions) - -Gin middleware for session management with multi-backend support: - -- [cookie-based](#cookie-based) -- [Redis](#redis) -- [memcached](#memcached) -- [MongoDB](#mongodb) -- [GORM](#gorm) -- [memstore](#memstore) -- [PostgreSQL](#postgresql) - -## Usage - -### Start using it - -Download and install it: - -```bash -go get github.com/gin-contrib/sessions -``` - -Import it in your code: - -```go -import "github.com/gin-contrib/sessions" -``` - -## Basic Examples - -### single session - -```go -package main - -import ( - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/cookie" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - store := cookie.NewStore([]byte("secret")) - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/hello", func(c *gin.Context) { - session := sessions.Default(c) - - if session.Get("hello") != "world" { - session.Set("hello", "world") - session.Save() - } - - c.JSON(200, gin.H{"hello": session.Get("hello")}) - }) - r.Run(":8000") -} -``` - -### multiple sessions - -```go -package main - -import ( - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/cookie" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - store := cookie.NewStore([]byte("secret")) - sessionNames := []string{"a", "b"} - r.Use(sessions.SessionsMany(sessionNames, store)) - - r.GET("/hello", func(c *gin.Context) { - sessionA := sessions.DefaultMany(c, "a") - sessionB := sessions.DefaultMany(c, "b") - - if sessionA.Get("hello") != "world!" { - sessionA.Set("hello", "world!") - sessionA.Save() - } - - if sessionB.Get("hello") != "world?" { - sessionB.Set("hello", "world?") - sessionB.Save() - } - - c.JSON(200, gin.H{ - "a": sessionA.Get("hello"), - "b": sessionB.Get("hello"), - }) - }) - r.Run(":8000") -} -``` - -## Backend Examples - -### cookie-based - -```go -package main - -import ( - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/cookie" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - store := cookie.NewStore([]byte("secret")) - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` - -### Redis - -```go -package main - -import ( - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/redis" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret")) - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` - -### Memcached - -#### ASCII Protocol - -```go -package main - -import ( - "github.com/bradfitz/gomemcache/memcache" - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/memcached" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - store := memcached.NewStore(memcache.New("localhost:11211"), "", []byte("secret")) - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` - -#### Binary protocol (with optional SASL authentication) - -```go -package main - -import ( - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/memcached" - "github.com/gin-gonic/gin" - "github.com/memcachier/mc" -) - -func main() { - r := gin.Default() - client := mc.NewMC("localhost:11211", "username", "password") - store := memcached.NewMemcacheStore(client, "", []byte("secret")) - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` - -### MongoDB - -#### mgo - -```go -package main - -import ( - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/mongo/mongomgo" - "github.com/gin-gonic/gin" - "github.com/globalsign/mgo" -) - -func main() { - r := gin.Default() - session, err := mgo.Dial("localhost:27017/test") - if err != nil { - // handle err - } - - c := session.DB("").C("sessions") - store := mongomgo.NewStore(c, 3600, true, []byte("secret")) - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` - -#### mongo-driver - -```go -package main - -import ( - "context" - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/mongo/mongodriver" - "github.com/gin-gonic/gin" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" -) - -func main() { - r := gin.Default() - mongoOptions := options.Client().ApplyURI("mongodb://localhost:27017") - client, err := mongo.NewClient(mongoOptions) - if err != nil { - // handle err - } - - if err := client.Connect(context.Background()); err != nil { - // handle err - } - - c := client.Database("test").Collection("sessions") - store := mongodriver.NewStore(c, 3600, true, []byte("secret")) - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` - -### memstore - -```go -package main - -import ( - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/memstore" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - store := memstore.NewStore([]byte("secret")) - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` - -### GORM - -```go -package main - -import ( - "github.com/gin-contrib/sessions" - gormsessions "github.com/gin-contrib/sessions/gorm" - "github.com/gin-gonic/gin" - "gorm.io/driver/sqlite" - "gorm.io/gorm" -) - -func main() { - db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) - if err != nil { - panic(err) - } - store := gormsessions.NewStore(db, true, []byte("secret")) - - r := gin.Default() - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` - -### PostgreSQL - -```go -package main - -import ( - "database/sql" - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/postgres" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - db, err := sql.Open("postgres", "postgresql://username:password@localhost:5432/database") - if err != nil { - // handle err - } - - store, err := postgres.NewStore(db, []byte("secret")) - if err != nil { - // handle err - } - - r.Use(sessions.Sessions("mysession", store)) - - r.GET("/incr", func(c *gin.Context) { - session := sessions.Default(c) - var count int - v := session.Get("count") - if v == nil { - count = 0 - } else { - count = v.(int) - count++ - } - session.Set("count", count) - session.Save() - c.JSON(200, gin.H{"count": count}) - }) - r.Run(":8000") -} -``` diff --git a/vendor/github.com/gin-contrib/sessions/memstore/memstore.go b/vendor/github.com/gin-contrib/sessions/memstore/memstore.go deleted file mode 100644 index 8826d6dd4..000000000 --- a/vendor/github.com/gin-contrib/sessions/memstore/memstore.go +++ /dev/null @@ -1,31 +0,0 @@ -package memstore - -import ( - "github.com/gin-contrib/sessions" - "github.com/quasoft/memstore" -) - -type Store interface { - sessions.Store -} - -// Keys are defined in pairs to allow key rotation, but the common case is to set a single -// authentication key and optionally an encryption key. -// -// The first key in a pair is used for authentication and the second for encryption. The -// encryption key can be set to nil or omitted in the last pair, but the authentication key -// is required in all pairs. -// -// It is recommended to use an authentication key with 32 or 64 bytes. The encryption key, -// if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes. -func NewStore(keyPairs ...[]byte) Store { - return &store{memstore.NewMemStore(keyPairs...)} -} - -type store struct { - *memstore.MemStore -} - -func (c *store) Options(options sessions.Options) { - c.MemStore.Options = options.ToGorillaOptions() -} diff --git a/vendor/github.com/gin-contrib/sessions/session_options_go1.10.go b/vendor/github.com/gin-contrib/sessions/session_options_go1.10.go deleted file mode 100644 index 68c880814..000000000 --- a/vendor/github.com/gin-contrib/sessions/session_options_go1.10.go +++ /dev/null @@ -1,31 +0,0 @@ -//go:build !go1.11 -// +build !go1.11 - -package sessions - -import ( - gsessions "github.com/gorilla/sessions" -) - -// Options stores configuration for a session or session store. -// Fields are a subset of http.Cookie fields. -type Options struct { - Path string - Domain string - // MaxAge=0 means no 'Max-Age' attribute specified. - // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'. - // MaxAge>0 means Max-Age attribute present and given in seconds. - MaxAge int - Secure bool - HttpOnly bool -} - -func (options Options) ToGorillaOptions() *gsessions.Options { - return &gsessions.Options{ - Path: options.Path, - Domain: options.Domain, - MaxAge: options.MaxAge, - Secure: options.Secure, - HttpOnly: options.HttpOnly, - } -} diff --git a/vendor/github.com/gin-contrib/sessions/session_options_go1.11.go b/vendor/github.com/gin-contrib/sessions/session_options_go1.11.go deleted file mode 100644 index 65da33872..000000000 --- a/vendor/github.com/gin-contrib/sessions/session_options_go1.11.go +++ /dev/null @@ -1,38 +0,0 @@ -//go:build go1.11 -// +build go1.11 - -package sessions - -import ( - "net/http" - - gsessions "github.com/gorilla/sessions" -) - -// Options stores configuration for a session or session store. -// Fields are a subset of http.Cookie fields. -type Options struct { - Path string - Domain string - // MaxAge=0 means no 'Max-Age' attribute specified. - // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'. - // MaxAge>0 means Max-Age attribute present and given in seconds. - MaxAge int - Secure bool - HttpOnly bool - // rfc-draft to preventing CSRF: https://tools.ietf.org/html/draft-west-first-party-cookies-07 - // refer: https://godoc.org/net/http - // https://www.sjoerdlangkemper.nl/2016/04/14/preventing-csrf-with-samesite-cookie-attribute/ - SameSite http.SameSite -} - -func (options Options) ToGorillaOptions() *gsessions.Options { - return &gsessions.Options{ - Path: options.Path, - Domain: options.Domain, - MaxAge: options.MaxAge, - Secure: options.Secure, - HttpOnly: options.HttpOnly, - SameSite: options.SameSite, - } -} diff --git a/vendor/github.com/gin-contrib/sessions/sessions.go b/vendor/github.com/gin-contrib/sessions/sessions.go deleted file mode 100644 index 0ef8ec414..000000000 --- a/vendor/github.com/gin-contrib/sessions/sessions.go +++ /dev/null @@ -1,152 +0,0 @@ -package sessions - -import ( - "log" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/gorilla/context" - "github.com/gorilla/sessions" -) - -const ( - DefaultKey = "github.com/gin-contrib/sessions" - errorFormat = "[sessions] ERROR! %s\n" -) - -type Store interface { - sessions.Store - Options(Options) -} - -// Wraps thinly gorilla-session methods. -// Session stores the values and optional configuration for a session. -type Session interface { - // ID of the session, generated by stores. It should not be used for user data. - ID() string - // Get returns the session value associated to the given key. - Get(key interface{}) interface{} - // Set sets the session value associated to the given key. - Set(key interface{}, val interface{}) - // Delete removes the session value associated to the given key. - Delete(key interface{}) - // Clear deletes all values in the session. - Clear() - // AddFlash adds a flash message to the session. - // A single variadic argument is accepted, and it is optional: it defines the flash key. - // If not defined "_flash" is used by default. - AddFlash(value interface{}, vars ...string) - // Flashes returns a slice of flash messages from the session. - // A single variadic argument is accepted, and it is optional: it defines the flash key. - // If not defined "_flash" is used by default. - Flashes(vars ...string) []interface{} - // Options sets configuration for a session. - Options(Options) - // Save saves all sessions used during the current request. - Save() error -} - -func Sessions(name string, store Store) gin.HandlerFunc { - return func(c *gin.Context) { - s := &session{name, c.Request, store, nil, false, c.Writer} - c.Set(DefaultKey, s) - defer context.Clear(c.Request) - c.Next() - } -} - -func SessionsMany(names []string, store Store) gin.HandlerFunc { - return func(c *gin.Context) { - sessions := make(map[string]Session, len(names)) - for _, name := range names { - sessions[name] = &session{name, c.Request, store, nil, false, c.Writer} - } - c.Set(DefaultKey, sessions) - defer context.Clear(c.Request) - c.Next() - } -} - -type session struct { - name string - request *http.Request - store Store - session *sessions.Session - written bool - writer http.ResponseWriter -} - -func (s *session) ID() string { - return s.Session().ID -} - -func (s *session) Get(key interface{}) interface{} { - return s.Session().Values[key] -} - -func (s *session) Set(key interface{}, val interface{}) { - s.Session().Values[key] = val - s.written = true -} - -func (s *session) Delete(key interface{}) { - delete(s.Session().Values, key) - s.written = true -} - -func (s *session) Clear() { - for key := range s.Session().Values { - s.Delete(key) - } -} - -func (s *session) AddFlash(value interface{}, vars ...string) { - s.Session().AddFlash(value, vars...) - s.written = true -} - -func (s *session) Flashes(vars ...string) []interface{} { - s.written = true - return s.Session().Flashes(vars...) -} - -func (s *session) Options(options Options) { - s.written = true - s.Session().Options = options.ToGorillaOptions() -} - -func (s *session) Save() error { - if s.Written() { - e := s.Session().Save(s.request, s.writer) - if e == nil { - s.written = false - } - return e - } - return nil -} - -func (s *session) Session() *sessions.Session { - if s.session == nil { - var err error - s.session, err = s.store.Get(s.request, s.name) - if err != nil { - log.Printf(errorFormat, err) - } - } - return s.session -} - -func (s *session) Written() bool { - return s.written -} - -// shortcut to get session -func Default(c *gin.Context) Session { - return c.MustGet(DefaultKey).(Session) -} - -// shortcut to get session with given name -func DefaultMany(c *gin.Context, name string) Session { - return c.MustGet(DefaultKey).(map[string]Session)[name] -} diff --git a/vendor/github.com/gin-contrib/sse/.golangci.yml b/vendor/github.com/gin-contrib/sse/.golangci.yml deleted file mode 100644 index 4c44c5fae..000000000 --- a/vendor/github.com/gin-contrib/sse/.golangci.yml +++ /dev/null @@ -1,3 +0,0 @@ -linters: - disable: - - errcheck diff --git a/vendor/github.com/gin-contrib/sse/.goreleaser.yaml b/vendor/github.com/gin-contrib/sse/.goreleaser.yaml deleted file mode 100644 index 4c910add4..000000000 --- a/vendor/github.com/gin-contrib/sse/.goreleaser.yaml +++ /dev/null @@ -1,29 +0,0 @@ -builds: - - # If true, skip the build. - # Useful for library projects. - # Default is false - skip: true - -changelog: - use: github - groups: - - title: Features - regexp: "^.*feat[(\\w)]*:+.*$" - order: 0 - - title: "Bug fixes" - regexp: "^.*fix[(\\w)]*:+.*$" - order: 1 - - title: "Enhancements" - regexp: "^.*chore[(\\w)]*:+.*$" - order: 2 - - title: "Refactor" - regexp: "^.*refactor[(\\w)]*:+.*$" - order: 3 - - title: "Build process updates" - regexp: ^.*?(build|ci)(\(.+\))??!?:.+$ - order: 4 - - title: "Documentation updates" - regexp: ^.*?docs?(\(.+\))??!?:.+$ - order: 4 - - title: Others - order: 999 diff --git a/vendor/github.com/gin-contrib/sse/LICENSE b/vendor/github.com/gin-contrib/sse/LICENSE deleted file mode 100644 index 1ff7f3706..000000000 --- a/vendor/github.com/gin-contrib/sse/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Manuel MartÃnez-Almeida - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/gin-contrib/sse/README.md b/vendor/github.com/gin-contrib/sse/README.md deleted file mode 100644 index cfe2c820b..000000000 --- a/vendor/github.com/gin-contrib/sse/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# Server-Sent Events - -[](https://pkg.go.dev/github.com/gin-contrib/sse) -[](https://github.com/gin-contrib/sse/actions/workflows/go.yml) -[](https://codecov.io/gh/gin-contrib/sse) -[](https://goreportcard.com/report/github.com/gin-contrib/sse) - -Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is [standardized as part of HTML5[1] by the W3C](http://www.w3.org/TR/2009/WD-eventsource-20091029/). - -- [Read this great SSE introduction by the HTML5Rocks guys](http://www.html5rocks.com/en/tutorials/eventsource/basics/) -- [Browser support](http://caniuse.com/#feat=eventsource) - -## Sample code - -```go -import "github.com/gin-contrib/sse" - -func httpHandler(w http.ResponseWriter, req *http.Request) { - // data can be a primitive like a string, an integer or a float - sse.Encode(w, sse.Event{ - Event: "message", - Data: "some data\nmore data", - }) - - // also a complex type, like a map, a struct or a slice - sse.Encode(w, sse.Event{ - Id: "124", - Event: "message", - Data: map[string]interface{}{ - "user": "manu", - "date": time.Now().Unix(), - "content": "hi!", - }, - }) -} -``` - -```sh -event: message -data: some data\\nmore data - -id: 124 -event: message -data: {"content":"hi!","date":1431540810,"user":"manu"} - -``` - -## Content-Type - -```go -fmt.Println(sse.ContentType) -``` - -```sh -text/event-stream -``` - -## Decoding support - -There is a client-side implementation of SSE coming soon. diff --git a/vendor/github.com/gin-contrib/sse/sse-decoder.go b/vendor/github.com/gin-contrib/sse/sse-decoder.go deleted file mode 100644 index fd49b9c37..000000000 --- a/vendor/github.com/gin-contrib/sse/sse-decoder.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package sse - -import ( - "bytes" - "io" - "io/ioutil" -) - -type decoder struct { - events []Event -} - -func Decode(r io.Reader) ([]Event, error) { - var dec decoder - return dec.decode(r) -} - -func (d *decoder) dispatchEvent(event Event, data string) { - dataLength := len(data) - if dataLength > 0 { - //If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer. - data = data[:dataLength-1] - dataLength-- - } - if dataLength == 0 && event.Event == "" { - return - } - if event.Event == "" { - event.Event = "message" - } - event.Data = data - d.events = append(d.events, event) -} - -func (d *decoder) decode(r io.Reader) ([]Event, error) { - buf, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - var currentEvent Event - var dataBuffer *bytes.Buffer = new(bytes.Buffer) - // TODO (and unit tests) - // Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, - // a single U+000A LINE FEED (LF) character, - // or a single U+000D CARRIAGE RETURN (CR) character. - lines := bytes.Split(buf, []byte{'\n'}) - for _, line := range lines { - if len(line) == 0 { - // If the line is empty (a blank line). Dispatch the event. - d.dispatchEvent(currentEvent, dataBuffer.String()) - - // reset current event and data buffer - currentEvent = Event{} - dataBuffer.Reset() - continue - } - if line[0] == byte(':') { - // If the line starts with a U+003A COLON character (:), ignore the line. - continue - } - - var field, value []byte - colonIndex := bytes.IndexRune(line, ':') - if colonIndex != -1 { - // If the line contains a U+003A COLON character character (:) - // Collect the characters on the line before the first U+003A COLON character (:), - // and let field be that string. - field = line[:colonIndex] - // Collect the characters on the line after the first U+003A COLON character (:), - // and let value be that string. - value = line[colonIndex+1:] - // If value starts with a single U+0020 SPACE character, remove it from value. - if len(value) > 0 && value[0] == ' ' { - value = value[1:] - } - } else { - // Otherwise, the string is not empty but does not contain a U+003A COLON character character (:) - // Use the whole line as the field name, and the empty string as the field value. - field = line - value = []byte{} - } - // The steps to process the field given a field name and a field value depend on the field name, - // as given in the following list. Field names must be compared literally, - // with no case folding performed. - switch string(field) { - case "event": - // Set the event name buffer to field value. - currentEvent.Event = string(value) - case "id": - // Set the event stream's last event ID to the field value. - currentEvent.Id = string(value) - case "retry": - // If the field value consists of only characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), - // then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer. - // Otherwise, ignore the field. - currentEvent.Id = string(value) - case "data": - // Append the field value to the data buffer, - dataBuffer.Write(value) - // then append a single U+000A LINE FEED (LF) character to the data buffer. - dataBuffer.WriteString("\n") - default: - //Otherwise. The field is ignored. - continue - } - } - // Once the end of the file is reached, the user agent must dispatch the event one final time. - d.dispatchEvent(currentEvent, dataBuffer.String()) - - return d.events, nil -} diff --git a/vendor/github.com/gin-contrib/sse/sse-encoder.go b/vendor/github.com/gin-contrib/sse/sse-encoder.go deleted file mode 100644 index 0d26c82f0..000000000 --- a/vendor/github.com/gin-contrib/sse/sse-encoder.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package sse - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "reflect" - "strconv" - "strings" -) - -// Server-Sent Events -// W3C Working Draft 29 October 2009 -// http://www.w3.org/TR/2009/WD-eventsource-20091029/ - -const ContentType = "text/event-stream;charset=utf-8" - -var contentType = []string{ContentType} -var noCache = []string{"no-cache"} - -var fieldReplacer = strings.NewReplacer( - "\n", "\\n", - "\r", "\\r") - -var dataReplacer = strings.NewReplacer( - "\n", "\ndata:", - "\r", "\\r") - -type Event struct { - Event string - Id string - Retry uint - Data interface{} -} - -func Encode(writer io.Writer, event Event) error { - w := checkWriter(writer) - writeId(w, event.Id) - writeEvent(w, event.Event) - writeRetry(w, event.Retry) - return writeData(w, event.Data) -} - -func writeId(w stringWriter, id string) { - if len(id) > 0 { - w.WriteString("id:") - fieldReplacer.WriteString(w, id) - w.WriteString("\n") - } -} - -func writeEvent(w stringWriter, event string) { - if len(event) > 0 { - w.WriteString("event:") - fieldReplacer.WriteString(w, event) - w.WriteString("\n") - } -} - -func writeRetry(w stringWriter, retry uint) { - if retry > 0 { - w.WriteString("retry:") - w.WriteString(strconv.FormatUint(uint64(retry), 10)) - w.WriteString("\n") - } -} - -func writeData(w stringWriter, data interface{}) error { - w.WriteString("data:") - - bData, ok := data.([]byte) - if ok { - dataReplacer.WriteString(w, string(bData)) - w.WriteString("\n\n") - return nil - } - - switch kindOfData(data) { - case reflect.Struct, reflect.Slice, reflect.Map: - err := json.NewEncoder(w).Encode(data) - if err != nil { - return err - } - w.WriteString("\n") - default: - dataReplacer.WriteString(w, fmt.Sprint(data)) - w.WriteString("\n\n") - } - return nil -} - -func (r Event) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - return Encode(w, r) -} - -func (r Event) WriteContentType(w http.ResponseWriter) { - header := w.Header() - header["Content-Type"] = contentType - - if _, exist := header["Cache-Control"]; !exist { - header["Cache-Control"] = noCache - } -} - -func kindOfData(data interface{}) reflect.Kind { - value := reflect.ValueOf(data) - valueType := value.Kind() - if valueType == reflect.Ptr { - valueType = value.Elem().Kind() - } - return valueType -} diff --git a/vendor/github.com/gin-contrib/sse/writer.go b/vendor/github.com/gin-contrib/sse/writer.go deleted file mode 100644 index 6f9806c55..000000000 --- a/vendor/github.com/gin-contrib/sse/writer.go +++ /dev/null @@ -1,24 +0,0 @@ -package sse - -import "io" - -type stringWriter interface { - io.Writer - WriteString(string) (int, error) -} - -type stringWrapper struct { - io.Writer -} - -func (w stringWrapper) WriteString(str string) (int, error) { - return w.Writer.Write([]byte(str)) -} - -func checkWriter(writer io.Writer) stringWriter { - if w, ok := writer.(stringWriter); ok { - return w - } else { - return stringWrapper{writer} - } -} |