diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f0b92624..56dfabef 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -2,9 +2,11 @@ version: 2 updates: - package-ecosystem: "gomod" directory: "/" + exclude-paths: + - "_examples/" schedule: - interval: "weekly" + interval: "monthly" - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "weekly" \ No newline at end of file + interval: "monthly" \ No newline at end of file diff --git a/apps/switch_hosts.go b/apps/switch_hosts.go index 25efec96..b4bc5155 100644 --- a/apps/switch_hosts.go +++ b/apps/switch_hosts.go @@ -19,7 +19,7 @@ type ( Pattern string // Target is the target Host that incoming requests will be redirected on pattern match // or an Application's Name that will handle the incoming request matched the Pattern. - Target interface{} // It was a string in my initial design but let's do that interface{}, we may support more types here in the future, until generics are in, keep it interface{}. + Target any // It was a string in my initial design but let's do that any, we may support more types here in the future, until generics are in, keep it any. } // Hosts is a switch provider. // It can be used as input argument to the `Switch` function diff --git a/context/application.go b/context/application.go index 15ce5abb..3b506ac9 100644 --- a/context/application.go +++ b/context/application.go @@ -30,7 +30,7 @@ type Application interface { // Validate validates a value and returns nil if passed or // the failure reason if not. - Validate(interface{}) error + Validate(any) error // Minifier returns the minifier instance. // By default it can minifies: @@ -44,7 +44,7 @@ type Application interface { // // Use context.View to render templates to the client instead. // Returns an error on failure, otherwise nil. - View(writer io.Writer, filename string, layout string, bindingData interface{}) error + View(writer io.Writer, filename string, layout string, bindingData any) error // GetContextPool returns the Iris sync.Pool which holds the contexts values. // Iris automatically releases the request context, so you don't have to use it. diff --git a/context/compress.go b/context/compress.go index fa673381..4b2f896b 100644 --- a/context/compress.go +++ b/context/compress.go @@ -170,7 +170,7 @@ func NewCompressReader(src io.Reader, encoding string) (*CompressReader, error) }, nil } -var compressWritersPool = sync.Pool{New: func() interface{} { return &CompressResponseWriter{} }} +var compressWritersPool = sync.Pool{New: func() any { return &CompressResponseWriter{} }} // AddCompressHeaders just adds the headers "Vary" to "Accept-Encoding" // and "Content-Encoding" to the given encoding. diff --git a/context/configuration.go b/context/configuration.go index c754577d..92a69d86 100644 --- a/context/configuration.go +++ b/context/configuration.go @@ -96,5 +96,5 @@ type ConfigurationReadOnly interface { // GetHostProxyHeaders returns the HostProxyHeaders field. GetHostProxyHeaders() map[string]bool // GetOther returns the Other field. - GetOther() map[string]interface{} + GetOther() map[string]any } diff --git a/context/context.go b/context/context.go index 337aad9a..af61e92b 100644 --- a/context/context.go +++ b/context/context.go @@ -84,7 +84,7 @@ type ( // Unmarshaler is the interface implemented by types that can unmarshal any raw data. // TIP INFO: Any pointer to a value which implements the BodyDecoder can be override the unmarshaler. Unmarshaler interface { - Unmarshal(data []byte, outPtr interface{}) error + Unmarshal(data []byte, outPtr any) error } // UnmarshalerFunc a shortcut for the Unmarshaler interface @@ -92,20 +92,20 @@ type ( // See 'Unmarshaler' and 'BodyDecoder' for more. // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-custom-via-unmarshaler/main.go - UnmarshalerFunc func(data []byte, outPtr interface{}) error + UnmarshalerFunc func(data []byte, outPtr any) error // DecodeFunc is a generic type of decoder function. // When the returned error is not nil the decode operation // is terminated and the error is received by the ReadJSONStream method, // otherwise it continues to read the next available object. // Look the `Context.ReadJSONStream` method. - DecodeFunc func(outPtr interface{}) error + DecodeFunc func(outPtr any) error ) // Unmarshal parses the X-encoded data and stores the result in the value pointed to by v. // Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, // slices, and pointers as necessary. -func (u UnmarshalerFunc) Unmarshal(data []byte, v interface{}) error { +func (u UnmarshalerFunc) Unmarshal(data []byte, v any) error { return u(data, v) } @@ -118,8 +118,8 @@ var LimitRequestBodySize = func(maxRequestBodySizeBytes int64) Handler { } } -// Map is just a type alias of the map[string]interface{} type. -type Map = map[string]interface{} +// Map is just a type alias of the map[string]any type. +type Map = map[string]any // Context is the midle-man server's "object" dealing with incoming requests. // @@ -433,7 +433,7 @@ type goroutines struct { mu sync.RWMutex } -var acquireGoroutines = func() interface{} { +var acquireGoroutines = func() any { return &goroutines{wg: new(sync.WaitGroup)} } @@ -840,7 +840,7 @@ func (ctx *Context) StopWithPlainError(statusCode int, err error) { // // If the status code is a failure one then // it will also fire the specified error code handler. -func (ctx *Context) StopWithJSON(statusCode int, jsonObject interface{}) error { +func (ctx *Context) StopWithJSON(statusCode int, jsonObject any) error { ctx.StopWithStatus(statusCode) return ctx.writeJSON(jsonObject, &DefaultJSONOptions) // do not modify - see errors.DefaultContextErrorHandler. } @@ -1359,7 +1359,7 @@ func (ctx *Context) GetLocale() Locale { // See `GetLocale` too. // // Example: https://github.com/kataras/iris/tree/main/_examples/i18n -func (ctx *Context) Tr(key string, args ...interface{}) string { +func (ctx *Context) Tr(key string, args ...any) string { return ctx.app.I18nReadOnly().TrContext(ctx, key, args...) } @@ -2692,17 +2692,17 @@ func (ctx *Context) GetBody() ([]byte, error) { // Validator is the validator for request body on Context methods such as // ReadJSON, ReadMsgPack, ReadXML, ReadYAML, ReadForm, ReadQuery, ReadBody and e.t.c. type Validator interface { - Struct(interface{}) error + Struct(any) error // If community asks for more than a struct validation on JSON, XML, MsgPack, Form, Query and e.t.c // then we should add more methods here, alternative approach would be to have a - // `Validator:Validate(interface{}) error` and a map[reflect.Kind]Validator instead. + // `Validator:Validate(any) error` and a map[reflect.Kind]Validator instead. } // UnmarshalBody reads the request's body and binds it to a value or pointer of any type // Examples of usage: context.ReadJSON, context.ReadXML. // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-custom-via-unmarshaler/main.go -func (ctx *Context) UnmarshalBody(outPtr interface{}, unmarshaler Unmarshaler) error { +func (ctx *Context) UnmarshalBody(outPtr any, unmarshaler Unmarshaler) error { if ctx.request.Body == nil { return fmt.Errorf("unmarshal: empty body: %w", ErrNotFound) } @@ -2766,7 +2766,7 @@ type JSONReader struct { // Note(@kataras): struct instead of optional funcs to ArrayStream bool } -var ReadJSON = func(ctx *Context, outPtr interface{}, opts ...JSONReader) error { +var ReadJSON = func(ctx *Context, outPtr any, opts ...JSONReader) error { var body io.Reader if ctx.IsRecordingBody() { @@ -2800,7 +2800,7 @@ var ReadJSON = func(ctx *Context, outPtr interface{}, opts ...JSONReader) error // ReadJSON reads JSON from request's body and binds it to a value of any json-valid type. // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-json/main.go -func (ctx *Context) ReadJSON(outPtr interface{}, opts ...JSONReader) error { +func (ctx *Context) ReadJSON(outPtr any, opts ...JSONReader) error { return ReadJSON(ctx, outPtr, opts...) } @@ -2846,14 +2846,14 @@ func (ctx *Context) ReadJSONStream(onDecode func(DecodeFunc) error, opts ...JSON // ReadXML reads XML from request's body and binds it to a value of any xml-valid type. // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-xml/main.go -func (ctx *Context) ReadXML(outPtr interface{}) error { +func (ctx *Context) ReadXML(outPtr any) error { return ctx.UnmarshalBody(outPtr, UnmarshalerFunc(xml.Unmarshal)) } // ReadYAML reads YAML from request's body and binds it to the "outPtr" value. // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-yaml/main.go -func (ctx *Context) ReadYAML(outPtr interface{}) error { +func (ctx *Context) ReadYAML(outPtr any) error { return ctx.UnmarshalBody(outPtr, UnmarshalerFunc(yaml.Unmarshal)) } @@ -2967,7 +2967,7 @@ const CSRFTokenFormKey = "csrf.token" // to change this behavior globally, set the `context.CSRFTokenFormKey` to an empty value. // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-form/main.go -func (ctx *Context) ReadForm(formObject interface{}) error { +func (ctx *Context) ReadForm(formObject any) error { values := ctx.FormValues() if len(values) == 0 { if ctx.app.ConfigurationReadOnly().GetFireEmptyFormError() { @@ -3124,7 +3124,7 @@ func distinctStrings(values []string) []string { // ReadQuery binds URL Query to "ptr". The struct field tag is "url". // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-query/main.go -func (ctx *Context) ReadQuery(ptr interface{}) error { +func (ctx *Context) ReadQuery(ptr any) error { values := ctx.getQuery() if len(values) == 0 { if ctx.app.ConfigurationReadOnly().GetFireEmptyFormError() { @@ -3144,7 +3144,7 @@ func (ctx *Context) ReadQuery(ptr interface{}) error { // ReadHeaders binds request headers to "ptr". The struct field tag is "header". // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-headers/main.go -func (ctx *Context) ReadHeaders(ptr interface{}) error { +func (ctx *Context) ReadHeaders(ptr any) error { err := schema.DecodeHeaders(ctx.request.Header, ptr) if err != nil { return err @@ -3156,7 +3156,7 @@ func (ctx *Context) ReadHeaders(ptr interface{}) error { // ReadParams binds URI Dynamic Path Parameters to "ptr". The struct field tag is "param". // // Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-params/main.go -func (ctx *Context) ReadParams(ptr interface{}) error { +func (ctx *Context) ReadParams(ptr any) error { n := ctx.params.Len() if n == 0 { return nil @@ -3183,7 +3183,7 @@ func (ctx *Context) ReadParams(ptr interface{}) error { // to the "ptr" pointer struct value. // The struct fields may contain "url" or "param" binding tags. // If a validator exists then it validates the result too. -func (ctx *Context) ReadURL(ptr interface{}) error { +func (ctx *Context) ReadURL(ptr any) error { values := make(map[string][]string, ctx.params.Len()) ctx.params.Visit(func(key string, value string) { values[key] = strings.Split(value, "/") @@ -3235,7 +3235,7 @@ func (ctx *Context) ReadJSONProtobuf(ptr proto.Message, opts ...ProtoUnmarshalOp } // ReadMsgPack binds the request body of msgpack format to the "ptr" and returns any error. -func (ctx *Context) ReadMsgPack(ptr interface{}) error { +func (ctx *Context) ReadMsgPack(ptr any) error { rawData, err := ctx.GetBody() if err != nil { return err @@ -3255,7 +3255,7 @@ func (ctx *Context) ReadMsgPack(ptr interface{}) error { // JSON, Protobuf, MsgPack, XML, YAML, MultipartForm and binds the result to the "ptr". // As a special case if the "ptr" was a pointer to string or []byte // then it will bind it to the request body as it is. -func (ctx *Context) ReadBody(ptr interface{}) error { +func (ctx *Context) ReadBody(ptr any) error { // If the ptr is string or byte, read the body as it's. switch v := ptr.(type) { case *string: @@ -3353,7 +3353,7 @@ func (ctx *Context) Write(rawBody []byte) (int, error) { // Writef formats according to a format specifier and writes to the response. // // Returns the number of bytes written and any write error encountered. -func (ctx *Context) Writef(format string, a ...interface{}) (n int, err error) { +func (ctx *Context) Writef(format string, a ...any) (n int, err error) { /* if len(a) == 0 { return ctx.WriteString(format) } ^ No, let it complain about arguments, because go test will do even if the app is running. @@ -3738,7 +3738,7 @@ func (ctx *Context) ViewLayout(layoutTmplFile string) { // Look .ViewLayout and .View too. // // Example: https://github.com/kataras/iris/tree/main/_examples/view/context-view-data/ -func (ctx *Context) ViewData(key string, value interface{}) { +func (ctx *Context) ViewData(key string, value any) { viewDataContextKey := ctx.app.ConfigurationReadOnly().GetViewDataContextKey() if key == "" { ctx.values.Set(viewDataContextKey, value) @@ -3757,7 +3757,7 @@ func (ctx *Context) ViewData(key string, value interface{}) { } // GetViewData returns the values registered by `context#ViewData`. -// The return value is `map[string]interface{}`, this means that +// The return value is `map[string]any`, this means that // if a custom struct registered to ViewData then this function // will try to parse it to map, if failed then the return value is nil // A check for nil is always a good practise if different @@ -3765,14 +3765,14 @@ func (ctx *Context) ViewData(key string, value interface{}) { // // Similarly to `viewData := ctx.Values().Get("iris.view.data")` or // `viewData := ctx.Values().Get(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey())`. -func (ctx *Context) GetViewData() map[string]interface{} { +func (ctx *Context) GetViewData() map[string]any { if v := ctx.values.Get(ctx.app.ConfigurationReadOnly().GetViewDataContextKey()); v != nil { - // if pure map[string]interface{} + // if pure map[string]any if viewData, ok := v.(Map); ok { return viewData } - // if struct, convert it to map[string]interface{} + // if struct, convert it to map[string]any if structs.IsStruct(v) { return structs.Map(v) } @@ -3936,7 +3936,7 @@ func (ctx *Context) FallbackView(providers ...FallbackViewProvider) { // Look .ViewData and .ViewLayout too. // // Examples: https://github.com/kataras/iris/tree/main/_examples/view -func (ctx *Context) View(filename string, optionalViewModel ...interface{}) error { +func (ctx *Context) View(filename string, optionalViewModel ...any) error { ctx.ContentType(ContentHTMLHeaderValue) err := ctx.renderView(filename, optionalViewModel...) @@ -3959,11 +3959,11 @@ func (ctx *Context) View(filename string, optionalViewModel ...interface{}) erro return err } -func (ctx *Context) renderView(filename string, optionalViewModel ...interface{}) error { +func (ctx *Context) renderView(filename string, optionalViewModel ...any) error { cfg := ctx.app.ConfigurationReadOnly() layout := ctx.values.GetString(cfg.GetViewLayoutContextKey()) - var bindingData interface{} + var bindingData any if len(optionalViewModel) > 0 /* Don't do it: can break a lot of servers: && optionalViewModel[0] != nil */ { // a nil can override the existing data or model sent by `ViewData`. bindingData = optionalViewModel[0] @@ -4124,7 +4124,7 @@ var ( secureJSONPrefix = []byte("while(1);") ) -func (ctx *Context) handleSpecialJSONResponseValue(v interface{}, options *JSON) (bool, int, error) { +func (ctx *Context) handleSpecialJSONResponseValue(v any, options *JSON) (bool, int, error) { if ctx.app.ConfigurationReadOnly().GetEnableProtoJSON() { if m, ok := v.(proto.Message); ok { protoJSON := ProtoMarshalOptions{} @@ -4160,7 +4160,7 @@ func (ctx *Context) handleSpecialJSONResponseValue(v interface{}, options *JSON) } // WriteJSON marshals the given interface object and writes the JSON response to the 'writer'. -var WriteJSON = func(ctx *Context, v interface{}, options *JSON) error { +var WriteJSON = func(ctx *Context, v any, options *JSON) error { if !options.Secure && !options.ASCII && options.Prefix == "" { // jsoniterConfig := jsoniter.Config{ // EscapeHTML: !options.UnescapeHTML, @@ -4343,7 +4343,7 @@ func (ctx *Context) RenderComponent(component Component) error { // // Customize the behavior of every `Context.JSON“ can be achieved // by modifying the package-level `WriteJSON` function on program initilization. -func (ctx *Context) JSON(v interface{}, opts ...JSON) (err error) { +func (ctx *Context) JSON(v any, opts ...JSON) (err error) { var options *JSON if len(opts) > 0 { options = &opts[0] @@ -4363,7 +4363,7 @@ func (ctx *Context) JSON(v interface{}, opts ...JSON) (err error) { return } -func (ctx *Context) writeJSON(v interface{}, options *JSON) error { +func (ctx *Context) writeJSON(v any, options *JSON) error { ctx.ContentType(ContentJSONHeaderValue) // After content type given and before everything else, try handle proto or easyjson, no matter the performance mode. @@ -4377,7 +4377,7 @@ func (ctx *Context) writeJSON(v interface{}, options *JSON) error { var finishCallbackB = []byte(");") // WriteJSONP marshals the given interface object and writes the JSONP response to the writer. -var WriteJSONP = func(ctx *Context, v interface{}, options *JSONP) (err error) { +var WriteJSONP = func(ctx *Context, v any, options *JSONP) (err error) { if callback := options.Callback; callback != "" { _, err = ctx.Write(stringToBytes(callback + "(")) if err != nil { @@ -4406,7 +4406,7 @@ var DefaultJSONPOptions = JSONP{} // It reports any JSON parser or write errors back to the caller. // Look the Application.SetContextErrorHandler to override the // default status code 500 with a custom error response. -func (ctx *Context) JSONP(v interface{}, opts ...JSONP) (err error) { +func (ctx *Context) JSONP(v any, opts ...JSONP) (err error) { var options *JSONP if len(opts) > 0 { options = &opts[0] @@ -4426,13 +4426,13 @@ func (ctx *Context) JSONP(v interface{}, opts ...JSONP) (err error) { type xmlMapEntry struct { XMLName xml.Name - Value interface{} `xml:",chardata"` + Value any `xml:",chardata"` } -// XMLMap wraps a map[string]interface{} to compatible xml marshaler, +// XMLMap wraps a map[string]any to compatible xml marshaler, // in order to be able to render maps as XML on the `Context.XML` method. // -// Example: `Context.XML(XMLMap("Root", map[string]interface{}{...})`. +// Example: `Context.XML(XMLMap("Root", map[string]any{...})`. func XMLMap(elementName string, v Map) xml.Marshaler { return xmlMap{ entries: v, @@ -4468,7 +4468,7 @@ func (m xmlMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { } // WriteXML marshals the given interface object and writes the XML response to the writer. -var WriteXML = func(ctx *Context, v interface{}, options *XML) error { +var WriteXML = func(ctx *Context, v any, options *XML) error { if prefix := options.Prefix; prefix != "" { _, err := ctx.Write(stringToBytes(prefix)) if err != nil { @@ -4495,7 +4495,7 @@ var DefaultXMLOptions = XML{} // It reports any XML parser or write errors back to the caller. // Look the Application.SetContextErrorHandler to override the // default status code 500 with a custom error response. -func (ctx *Context) XML(v interface{}, opts ...XML) (err error) { +func (ctx *Context) XML(v any, opts ...XML) (err error) { var options *XML if len(opts) > 0 { options = &opts[0] @@ -4524,7 +4524,7 @@ func (ctx *Context) XML(v interface{}, opts ...XML) (err error) { // send a response of content type "application/problem+xml" instead. // // Read more at: https://github.com/kataras/iris/blob/main/_examples/routing/http-errors. -func (ctx *Context) Problem(v interface{}, opts ...ProblemOptions) error { +func (ctx *Context) Problem(v any, opts ...ProblemOptions) error { options := DefaultProblemOptions if len(opts) > 0 { options = opts[0] @@ -4605,7 +4605,7 @@ func (ctx *Context) Markdown(markdownB []byte, opts ...Markdown) (err error) { } // WriteYAML sends YAML response to the client. -var WriteYAML = func(ctx *Context, v interface{}, indentSpace int) error { +var WriteYAML = func(ctx *Context, v any, indentSpace int) error { encoder := yaml.NewEncoder(ctx.writer) encoder.SetIndent(indentSpace) @@ -4621,7 +4621,7 @@ var WriteYAML = func(ctx *Context, v interface{}, indentSpace int) error { // It reports any YAML parser or write errors back to the caller. // Look the Application.SetContextErrorHandler to override the // default status code 500 with a custom error response. -func (ctx *Context) YAML(v interface{}) error { +func (ctx *Context) YAML(v any) error { ctx.ContentType(ContentYAMLHeaderValue) err := WriteYAML(ctx, v, 0) @@ -4634,7 +4634,7 @@ func (ctx *Context) YAML(v interface{}) error { } // TextYAML calls the Context.YAML method but with the text/yaml content type instead. -func (ctx *Context) TextYAML(v interface{}) error { +func (ctx *Context) TextYAML(v any) error { ctx.ContentType(ContentYAMLTextHeaderValue) err := WriteYAML(ctx, v, 4) @@ -4672,7 +4672,7 @@ func (ctx *Context) Protobuf(v proto.Message) (int, error) { // It reports any message pack or write errors back to the caller. // Look the Application.SetContextErrorHandler to override the // default status code 500 with a custom error response. -func (ctx *Context) MsgPack(v interface{}) (int, error) { +func (ctx *Context) MsgPack(v any) (int, error) { out, err := msgpack.Marshal(v) if err != nil { ctx.handleContextError(err) @@ -4702,7 +4702,7 @@ var ErrContentNotSupported = errors.New("unsupported content") // // See the `N` struct too. type ContentSelector interface { - SelectContent(mime string) interface{} + SelectContent(mime string) any } // ContentNegotiator is the interface which structs can implement @@ -4732,13 +4732,13 @@ type N struct { Markdown []byte Binary []byte - JSON interface{} + JSON any Problem Problem - JSONP interface{} - XML interface{} - YAML interface{} - Protobuf interface{} - MsgPack interface{} + JSONP any + XML any + YAML any + Protobuf any + MsgPack any Other []byte // custom content types. } @@ -4746,7 +4746,7 @@ type N struct { var _ ContentSelector = N{} // SelectContent returns a content based on the matched negotiated "mime". -func (n N) SelectContent(mime string) interface{} { +func (n N) SelectContent(mime string) any { switch mime { case ContentTextHeaderValue: return n.Text @@ -4842,7 +4842,7 @@ func parseHeader(headerValue string) []string { // Supports the above without quality values. // // Read more at: https://github.com/kataras/iris/tree/main/_examples/response-writer/content-negotiation -func (ctx *Context) Negotiate(v interface{}) (int, error) { +func (ctx *Context) Negotiate(v any) (int, error) { contentType, charset, encoding, content := ctx.Negotiation().Build() if v == nil { v = content @@ -4977,8 +4977,8 @@ func (ctx *Context) Negotiate(v interface{}) (int, error) { type NegotiationBuilder struct { Accept NegotiationAcceptBuilder - mime []string // we need order. - contents map[string]interface{} // map to the "mime" and content should be rendered if that mime requested. + mime []string // we need order. + contents map[string]any // map to the "mime" and content should be rendered if that mime requested. charset []string encoding []string } @@ -4987,7 +4987,7 @@ type NegotiationBuilder struct { // through `Context.Negotiate` when this mime type is accepted by client. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) MIME(mime string, content interface{}) *NegotiationBuilder { +func (n *NegotiationBuilder) MIME(mime string, content any) *NegotiationBuilder { mimes := parseHeader(mime) // if contains more than one sep by commas ",". if content == nil { n.mime = append(n.mime, mimes...) @@ -4995,7 +4995,7 @@ func (n *NegotiationBuilder) MIME(mime string, content interface{}) *Negotiation } if n.contents == nil { - n.contents = make(map[string]interface{}) + n.contents = make(map[string]any) } for _, m := range mimes { @@ -5012,7 +5012,7 @@ func (n *NegotiationBuilder) MIME(mime string, content interface{}) *Negotiation // // Returns itself for recursive calls. func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder { - var content interface{} + var content any if len(v) > 0 { content = v[0] } @@ -5025,7 +5025,7 @@ func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder { // // Returns itself for recursive calls. func (n *NegotiationBuilder) HTML(v ...string) *NegotiationBuilder { - var content interface{} + var content any if len(v) > 0 { content = v[0] } @@ -5038,7 +5038,7 @@ func (n *NegotiationBuilder) HTML(v ...string) *NegotiationBuilder { // // Returns itself for recursive calls. func (n *NegotiationBuilder) Markdown(v ...[]byte) *NegotiationBuilder { - var content interface{} + var content any if len(v) > 0 { content = v } @@ -5051,7 +5051,7 @@ func (n *NegotiationBuilder) Markdown(v ...[]byte) *NegotiationBuilder { // // Returns itself for recursive calls. func (n *NegotiationBuilder) Binary(v ...[]byte) *NegotiationBuilder { - var content interface{} + var content any if len(v) > 0 { content = v[0] } @@ -5063,8 +5063,8 @@ func (n *NegotiationBuilder) Binary(v ...[]byte) *NegotiationBuilder { // when a client accepts the "application/json" content type. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) JSON(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) JSON(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5076,8 +5076,8 @@ func (n *NegotiationBuilder) JSON(v ...interface{}) *NegotiationBuilder { // when a client accepts the "application/problem+json" or the "application/problem+xml" content type. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) Problem(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) Problem(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5089,8 +5089,8 @@ func (n *NegotiationBuilder) Problem(v ...interface{}) *NegotiationBuilder { // when a client accepts the "javascript/javascript" content type. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) JSONP(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) JSONP(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5102,8 +5102,8 @@ func (n *NegotiationBuilder) JSONP(v ...interface{}) *NegotiationBuilder { // when a client accepts one of the "text/xml" or "application/xml" content types. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) XML(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) XML(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5115,8 +5115,8 @@ func (n *NegotiationBuilder) XML(v ...interface{}) *NegotiationBuilder { // when a client accepts the "application/x-yaml" content type. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) YAML(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) YAML(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5128,8 +5128,8 @@ func (n *NegotiationBuilder) YAML(v ...interface{}) *NegotiationBuilder { // when a client accepts the "application/x-yaml" content type. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) TextYAML(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) TextYAML(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5141,8 +5141,8 @@ func (n *NegotiationBuilder) TextYAML(v ...interface{}) *NegotiationBuilder { // when a client accepts the "application/x-protobuf" content type. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) Protobuf(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) Protobuf(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5154,8 +5154,8 @@ func (n *NegotiationBuilder) Protobuf(v ...interface{}) *NegotiationBuilder { // when a client accepts one of the "application/x-msgpack" or "application/msgpack" content types. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) MsgPack(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) MsgPack(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5165,8 +5165,8 @@ func (n *NegotiationBuilder) MsgPack(v ...interface{}) *NegotiationBuilder { // Any registers a wildcard that can match any client's accept content type. // // Returns itself for recursive calls. -func (n *NegotiationBuilder) Any(v ...interface{}) *NegotiationBuilder { - var content interface{} +func (n *NegotiationBuilder) Any(v ...any) *NegotiationBuilder { + var content any if len(v) > 0 { content = v[0] } @@ -5209,7 +5209,7 @@ func (n *NegotiationBuilder) EncodingGzip() *NegotiationBuilder { // // The returned "content" can be nil if the matched "contentType" does not provide any value, // in that case the `Context.Negotiate(v)` must be called with a non-nil value. -func (n *NegotiationBuilder) Build() (contentType, charset, encoding string, content interface{}) { +func (n *NegotiationBuilder) Build() (contentType, charset, encoding string, content any) { contentType = negotiationMatch(n.Accept.accept, n.mime) charset = negotiationMatch(n.Accept.charset, n.charset) encoding = negotiationMatch(n.Accept.encoding, n.encoding) @@ -5753,7 +5753,7 @@ type SecureCookie interface { // You either need to provide exactly that amount or you derive the key from what you type in. // // See `Decode` too. - Encode(cookieName string, cookieValue interface{}) (string, error) + Encode(cookieName string, cookieValue any) (string, error) // Decode should decode the cookie value. // Should accept the cookie's name as its first argument, // as second argument the encoded cookie value and as third argument the decoded value ptr. @@ -5765,7 +5765,7 @@ type SecureCookie interface { // You either need to provide exactly that amount or you derive the key from what you type in. // // See `Encode` too. - Decode(cookieName string, cookieValue string, cookieValuePtr interface{}) error + Decode(cookieName string, cookieValue string, cookieValuePtr any) error } // CookieEncoding accepts a value which implements `Encode` and `Decode` methods. @@ -6202,7 +6202,7 @@ type DependenciesMap map[reflect.Type]reflect.Value // in sake of minimum performance cost. // // See `UnregisterDependency` too. -func (ctx *Context) RegisterDependency(v interface{}) { +func (ctx *Context) RegisterDependency(v any) { if v == nil { return } @@ -6350,7 +6350,7 @@ func (ctx *Context) GetErrPublic() (bool, error) { // which recovers from a manual panic. type ErrPanicRecovery struct { ErrPrivate - Cause interface{} + Cause any Callers []string // file:line callers. Stack []byte // the full debug stack. RegisteredHandlers []string // file:line of all registered handlers. @@ -6436,7 +6436,7 @@ const ( // // Example at: // https://github.com/kataras/iris/tree/main/_examples/routing/writing-a-middleware/share-funcs -func (ctx *Context) SetFunc(name string, fn interface{}, persistenceArgs ...interface{}) { +func (ctx *Context) SetFunc(name string, fn any, persistenceArgs ...any) { f := newFunc(name, fn, persistenceArgs...) ctx.values.Set(funcsContextPrefixKey+name, f) } @@ -6467,7 +6467,7 @@ func (ctx *Context) GetFunc(name string) (*Func, bool) { // // For a more complete solution without limiations navigate through // the Iris Dependency Injection feature instead. -func (ctx *Context) CallFunc(name string, args ...interface{}) ([]reflect.Value, error) { +func (ctx *Context) CallFunc(name string, args ...any) ([]reflect.Value, error) { fn, ok := ctx.GetFunc(name) if !ok || fn == nil { return nil, ErrNotFound @@ -6484,14 +6484,14 @@ func (ctx *Context) CallFunc(name string, args ...interface{}) ([]reflect.Value, // This method uses the `SetFunc` method under the hoods. // // See `Logout` method too. -func (ctx *Context) SetLogoutFunc(fn interface{}, persistenceArgs ...interface{}) { +func (ctx *Context) SetLogoutFunc(fn any, persistenceArgs ...any) { ctx.SetFunc(funcLogoutContextKey, fn, persistenceArgs...) } // Logout calls the registered logout function. // Returns ErrNotFound if a logout function was not specified // by a prior call of `SetLogoutFunc`. -func (ctx *Context) Logout(args ...interface{}) error { +func (ctx *Context) Logout(args ...any) error { _, err := ctx.CallFunc(funcLogoutContextKey, args...) return err } @@ -6505,13 +6505,13 @@ const userContextKey = "iris.user" // // The "i" input argument can be: // - A value which completes the User interface -// - A map[string]interface{}. +// - A map[string]any. // - A value which does not complete the whole User interface // - A value which does not complete the User interface at all // (only its `User().GetRaw` method is available). // // Look the `User` method to retrieve it. -func (ctx *Context) SetUser(i interface{}) error { +func (ctx *Context) SetUser(i any) error { if i == nil { ctx.values.Remove(userContextKey) return nil @@ -6615,8 +6615,8 @@ func (ctx *Context) Err() error { // if no value is associated with key. Successive calls to Value with // the same key returns the same result. // -// Shortcut of Request().Context().Value(key interface{}) interface{}. -func (ctx *Context) Value(key interface{}) interface{} { +// Shortcut of Request().Context().Value(key any) any. +func (ctx *Context) Value(key any) any { if keyStr, ok := key.(string); ok { // check if the key is a type of string, which can be retrieved by the mem store. if entry, exists := ctx.values.GetEntry(keyStr); exists { return entry.ValueRaw @@ -6633,14 +6633,14 @@ const idContextKey = "iris.context.id" // so it can be rendered on `Context.String` method. // // See `GetID` and `middleware/requestid` too. -func (ctx *Context) SetID(id interface{}) { +func (ctx *Context) SetID(id any) { ctx.values.Set(idContextKey, id) } // GetID returns the Request Context's ID. // It returns nil if not given by a prior `SetID` call. // See `middleware/requestid` too. -func (ctx *Context) GetID() interface{} { +func (ctx *Context) GetID() any { return ctx.values.Get(idContextKey) } diff --git a/context/context_func.go b/context/context_func.go index 4d04d700..b9569e0e 100644 --- a/context/context_func.go +++ b/context/context_func.go @@ -13,16 +13,16 @@ var ErrInvalidArgs = errors.New("invalid arguments") // Func represents a function registered by the Context. // See its `buildMeta` and `call` internal methods. type Func struct { - RegisterName string // the name of which this function is registered, for information only. - Raw interface{} // the Raw function, can be used for custom casting. - PersistenceArgs []interface{} // the persistence input arguments given on registration. + RegisterName string // the name of which this function is registered, for information only. + Raw any // the Raw function, can be used for custom casting. + PersistenceArgs []any // the persistence input arguments given on registration. once sync.Once // guards build once, on first call. // Available after the first call. Meta *FuncMeta } -func newFunc(name string, fn interface{}, persistenceArgs ...interface{}) *Func { +func newFunc(name string, fn any, persistenceArgs ...any) *Func { return &Func{ RegisterName: name, Raw: fn, @@ -37,8 +37,8 @@ type FuncMeta struct { HandlerWithErr func(*Context) error // when it's just a handler which returns an error. RawFunc func() // when it's just a func. RawFuncWithErr func() error // when it's just a func which returns an error. - RawFuncArgs func(...interface{}) - RawFuncArgsWithErr func(...interface{}) error + RawFuncArgs func(...any) + RawFuncArgsWithErr func(...any) error Value reflect.Value Type reflect.Type @@ -65,10 +65,10 @@ func (f *Func) buildMeta() { case func() error: f.Meta = &FuncMeta{RawFuncWithErr: fn} return - case func(...interface{}): + case func(...any): f.Meta = &FuncMeta{RawFuncArgs: fn} return - case func(...interface{}) error: + case func(...any) error: f.Meta = &FuncMeta{RawFuncArgsWithErr: fn} return } @@ -119,7 +119,7 @@ func (f *Func) buildMeta() { f.Meta = &meta } -func (f *Func) call(ctx *Context, args ...interface{}) ([]reflect.Value, error) { +func (f *Func) call(ctx *Context, args ...any) ([]reflect.Value, error) { f.once.Do(f.buildMeta) meta := f.Meta diff --git a/context/context_user.go b/context/context_user.go index 3b138c05..3af8ce7d 100644 --- a/context/context_user.go +++ b/context/context_user.go @@ -34,7 +34,7 @@ var ErrNotSupported = errors.New("not supported") // - UserPartial (a wrapper by SetUser) type User interface { // GetRaw should return the raw instance of the user, if supported. - GetRaw() (interface{}, error) + GetRaw() (any, error) // GetAuthorization should return the authorization method, // e.g. Basic Authentication. GetAuthorization() (string, error) @@ -60,12 +60,12 @@ type User interface { // GetField should optionally return a dynamic field // based on its key. Useful for custom user fields. // Keep in mind that these fields are encoded as a separate JSON key. - GetField(key string) (interface{}, error) + GetField(key string) (any, error) } /* Notes: We could use a structure of User wrapper and separate interfaces for each of the methods so they return ErrNotSupported if the implementation is missing it, so the `Features` field and HasUserFeature can be omitted and -add a Raw() interface{} to return the underline User implementation too. +add a Raw() any to return the underline User implementation too. The advandages of the above idea is that we don't have to add new methods for each of the builtin features and we can keep the (assumed) struct small. But we dont as it has many disadvantages, unless is requested. @@ -95,7 +95,7 @@ type SimpleUser struct { var _ User = (*SimpleUser)(nil) // GetRaw returns itself. -func (u *SimpleUser) GetRaw() (interface{}, error) { +func (u *SimpleUser) GetRaw() (any, error) { return u, nil } @@ -156,7 +156,7 @@ func (u *SimpleUser) GetToken() ([]byte, error) { // GetField optionally returns a dynamic field from the `Fields` field // based on its key. -func (u *SimpleUser) GetField(key string) (interface{}, error) { +func (u *SimpleUser) GetField(key string) (any, error) { if u.Fields == nil { return nil, ErrNotSupported } @@ -164,10 +164,10 @@ func (u *SimpleUser) GetField(key string) (interface{}, error) { return u.Fields[key], nil } -// UserMap can be used to convert a common map[string]interface{} to a User. +// UserMap can be used to convert a common map[string]any to a User. // Usage: // -// user := map[string]interface{}{ +// user := map[string]any{ // "username": "kataras", // "age" : 27, // } @@ -189,7 +189,7 @@ type UserMap Map var _ User = UserMap{} // GetRaw returns the underline map. -func (u UserMap) GetRaw() (interface{}, error) { +func (u UserMap) GetRaw() (any, error) { return Map(u), nil } @@ -235,11 +235,11 @@ func (u UserMap) GetToken() ([]byte, error) { // GetField returns the raw map's value based on its "key". // It's not kind of useful here as you can just use the map. -func (u UserMap) GetField(key string) (interface{}, error) { +func (u UserMap) GetField(key string) (any, error) { return u[key], nil } -func (u UserMap) val(key string) interface{} { +func (u UserMap) val(key string) any { isTitle := unicode.IsTitle(rune(key[0])) // if starts with uppercase. if isTitle { key = strings.ToLower(key) @@ -333,7 +333,7 @@ type ( } userGetField interface { - GetField(string) interface{} + GetField(string) any } // UserPartial is a User. @@ -341,7 +341,7 @@ type ( // may or may not complete the whole User interface. // See Context.SetUser. UserPartial struct { - Raw interface{} `json:"raw"` + Raw any `json:"raw"` userGetAuthorization `json:",omitempty"` userGetAuthorizedAt `json:",omitempty"` userGetID `json:",omitempty"` @@ -356,7 +356,7 @@ type ( var _ User = (*UserPartial)(nil) -func newUserPartial(i interface{}) *UserPartial { +func newUserPartial(i any) *UserPartial { if i == nil { return nil } @@ -407,7 +407,7 @@ func newUserPartial(i interface{}) *UserPartial { } // GetRaw returns the original raw instance of the user. -func (u *UserPartial) GetRaw() (interface{}, error) { +func (u *UserPartial) GetRaw() (any, error) { if u == nil { return nil, ErrNotSupported } @@ -496,7 +496,7 @@ func (u *UserPartial) GetToken() ([]byte, error) { // GetField should optionally return a dynamic field // based on its key. Useful for custom user fields. // Keep in mind that these fields are encoded as a separate JSON key. -func (u *UserPartial) GetField(key string) (interface{}, error) { +func (u *UserPartial) GetField(key string) (any, error) { if v := u.userGetField; v != nil { return v.GetField(key), nil } diff --git a/context/fs.go b/context/fs.go index ce7499dc..39a6b596 100644 --- a/context/fs.go +++ b/context/fs.go @@ -17,7 +17,7 @@ import ( // It affects the view engine's filesystem resolver. // // This package-level variable can be modified on initialization. -var ResolveFS = func(fsOrDir interface{}) fs.FS { +var ResolveFS = func(fsOrDir any) fs.FS { if fsOrDir == nil { return noOpFS{} } @@ -101,7 +101,7 @@ func (f *httpFS) ReadDir(name string) ([]fs.DirEntry, error) { // It affects the Application's API Builder's `HandleDir` method. // // This package-level variable can be modified on initialization. -var ResolveHTTPFS = func(fsOrDir interface{}) http.FileSystem { +var ResolveHTTPFS = func(fsOrDir any) http.FileSystem { var fileSystem http.FileSystem switch v := fsOrDir.(type) { case string: diff --git a/context/handler.go b/context/handler.go index 9ffeede9..41a51913 100644 --- a/context/handler.go +++ b/context/handler.go @@ -131,7 +131,7 @@ type Handler = func(*Context) // See `Handler` for more. type Handlers = []Handler -func valueOf(v interface{}) reflect.Value { +func valueOf(v any) reflect.Value { if val, ok := v.(reflect.Value); ok { return val } @@ -142,7 +142,7 @@ func valueOf(v interface{}) reflect.Value { // HandlerName returns the handler's function name. // See `Context.HandlerName` method to get function name of the current running handler in the chain. // See `SetHandlerName` too. -func HandlerName(h interface{}) string { +func HandlerName(h any) string { pc := valueOf(h).Pointer() fn := runtime.FuncForPC(pc) name := fn.Name() @@ -166,10 +166,10 @@ func HandlerName(h interface{}) string { // or to determinate if end-developer // called the same exactly Use/UseRouter/Done... API methods // so framework can give a warning. -func HandlersNames(handlers ...interface{}) string { +func HandlersNames(handlers ...any) string { if len(handlers) == 1 { if hs, ok := handlers[0].(Handlers); ok { - asInterfaces := make([]interface{}, 0, len(hs)) + asInterfaces := make([]any, 0, len(hs)) for _, h := range hs { asInterfaces = append(asInterfaces, h) } @@ -188,14 +188,14 @@ func HandlersNames(handlers ...interface{}) string { // HandlerFileLine returns the handler's file and line information. // See `context.HandlerFileLine` to get the file, line of the current running handler in the chain. -func HandlerFileLine(h interface{}) (file string, line int) { +func HandlerFileLine(h any) (file string, line int) { pc := valueOf(h).Pointer() return runtime.FuncForPC(pc).FileLine(pc) } // HandlerFileLineRel same as `HandlerFileLine` but it returns the path // corresponding to its relative based on the package-level "WorkingDir" variable. -func HandlerFileLineRel(h interface{}) (file string, line int) { +func HandlerFileLineRel(h any) (file string, line int) { file, line = HandlerFileLine(h) if relFile, err := filepath.Rel(WorkingDir, file); err == nil { if !strings.HasPrefix(relFile, "..") { @@ -209,13 +209,13 @@ func HandlerFileLineRel(h interface{}) (file string, line int) { // MainHandlerName tries to find the main handler that end-developer // registered on the provided chain of handlers and returns its function name. -func MainHandlerName(handlers ...interface{}) (name string, index int) { +func MainHandlerName(handlers ...any) (name string, index int) { if len(handlers) == 0 { return } if hs, ok := handlers[0].(Handlers); ok { - tmp := make([]interface{}, 0, len(hs)) + tmp := make([]any, 0, len(hs)) for _, h := range hs { tmp = append(tmp, h) } diff --git a/context/i18n.go b/context/i18n.go index 726cd009..a1793fe4 100644 --- a/context/i18n.go +++ b/context/i18n.go @@ -7,8 +7,8 @@ import "golang.org/x/text/language" type I18nReadOnly interface { Tags() []language.Tag GetLocale(ctx *Context) Locale - Tr(lang string, key string, args ...interface{}) string - TrContext(ctx *Context, key string, args ...interface{}) string + Tr(lang string, key string, args ...any) string + TrContext(ctx *Context, key string, args ...any) string } // Locale is the interface which returns from a `Localizer.GetLocale` method. @@ -25,5 +25,5 @@ type Locale interface { // Same as `Tag().String()` but it's static. Language() string // GetMessage should return translated text based on the given "key". - GetMessage(key string, args ...interface{}) string + GetMessage(key string, args ...any) string } diff --git a/context/pool.go b/context/pool.go index 23eb9686..7f30490e 100644 --- a/context/pool.go +++ b/context/pool.go @@ -11,7 +11,7 @@ type Pool struct { } // New creates and returns a new context pool. -func New(newFunc func() interface{}) *Pool { +func New(newFunc func() any) *Pool { return &Pool{pool: &sync.Pool{New: newFunc}} } diff --git a/context/problem.go b/context/problem.go index 2d4a86c4..e0b355be 100644 --- a/context/problem.go +++ b/context/problem.go @@ -15,7 +15,7 @@ import ( // write an "application/problem+json" response. // // Read more at: https://github.com/kataras/iris/blob/main/_examples/routing/http-errors. -type Problem map[string]interface{} +type Problem map[string]any // NewProblem retruns a new Problem. // Head over to the `Problem` type godoc for more. @@ -99,12 +99,12 @@ const ( // TempKey sets a temporary key-value pair, which is being removed // on the its first get. -func (p Problem) TempKey(key string, value interface{}) Problem { +func (p Problem) TempKey(key string, value any) Problem { return p.Key(problemTempKeyPrefix+key, value) } // GetTempKey returns the temp value based on "key" and removes it. -func (p Problem) GetTempKey(key string) interface{} { +func (p Problem) GetTempKey(key string) any { key = problemTempKeyPrefix + key v, ok := p[key] if ok { @@ -116,7 +116,7 @@ func (p Problem) GetTempKey(key string) interface{} { } // Key sets a custom key-value pair. -func (p Problem) Key(key string, value interface{}) Problem { +func (p Problem) Key(key string, value any) Problem { p[key] = value return p } @@ -277,20 +277,20 @@ type ProblemOptions struct { // 300 * time.Second, // "5m", // 300 - RetryAfter interface{} + RetryAfter any // A function that, if specified, can dynamically set // retry-after based on the request. Useful for ProblemOptions reusability. // Should return time.Time, time.Duration, int64, int, float64 or string. // // Overrides the RetryAfter field. - RetryAfterFunc func(*Context) interface{} + RetryAfterFunc func(*Context) any } func parseDurationToSeconds(dur time.Duration) int64 { return int64(math.Round(dur.Seconds())) } -func (o *ProblemOptions) parseRetryAfter(value interface{}, timeLayout string) string { +func (o *ProblemOptions) parseRetryAfter(value any, timeLayout string) string { // https://tools.ietf.org/html/rfc7231#section-7.1.3 // Retry-After = HTTP-date / delay-seconds switch v := value.(type) { diff --git a/context/request_params.go b/context/request_params.go index 7d8fec45..b2c2d95c 100644 --- a/context/request_params.go +++ b/context/request_params.go @@ -70,7 +70,7 @@ func (r *RequestParams) GetEntry(key string) memstore.Entry { // Visit accepts a visitor which will be filled // by the key-value params. func (r *RequestParams) Visit(visitor func(key string, value string)) { - r.Store.Visit(func(k string, v interface{}) { + r.Store.Visit(func(k string, v any) { visitor(k, fmt.Sprintf("%v", v)) // always string here. }) } @@ -227,7 +227,7 @@ func (r *RequestParams) GetIntUnslashed(key string) (int, bool) { // The value is a function which accepts the parameter index // and it should return the value as the parameter type evaluator expects it. // -// i.e [reflect.TypeOf("string")] = func(paramIndex int) interface{} { +// i.e [reflect.TypeOf("string")] = func(paramIndex int) any { // return func(ctx *Context) { // return ctx.Params().GetEntryAt(paramIndex).ValueRaw.() // } @@ -238,8 +238,8 @@ func (r *RequestParams) GetIntUnslashed(key string) (int, bool) { // and parameter index based on the hero/mvc function added // in order to support the MVC.HandleMany("GET", "/path/{ps}/{pssecond} /path/{ps}") // when on the second requested path, the 'pssecond' should be empty. -var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ - reflect.TypeOf(""): func(paramIndex int) interface{} { +var ParamResolvers = map[reflect.Type]func(paramIndex int) any{ + reflect.TypeOf(""): func(paramIndex int) any { return func(ctx *Context) string { if ctx.Params().Len() <= paramIndex { return "" @@ -247,7 +247,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(string) } }, - reflect.TypeOf(int(1)): func(paramIndex int) interface{} { + reflect.TypeOf(int(1)): func(paramIndex int) any { return func(ctx *Context) int { if ctx.Params().Len() <= paramIndex { return 0 @@ -257,7 +257,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int) } }, - reflect.TypeOf(int8(1)): func(paramIndex int) interface{} { + reflect.TypeOf(int8(1)): func(paramIndex int) any { return func(ctx *Context) int8 { if ctx.Params().Len() <= paramIndex { return 0 @@ -265,7 +265,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int8) } }, - reflect.TypeOf(int16(1)): func(paramIndex int) interface{} { + reflect.TypeOf(int16(1)): func(paramIndex int) any { return func(ctx *Context) int16 { if ctx.Params().Len() <= paramIndex { return 0 @@ -273,7 +273,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int16) } }, - reflect.TypeOf(int32(1)): func(paramIndex int) interface{} { + reflect.TypeOf(int32(1)): func(paramIndex int) any { return func(ctx *Context) int32 { if ctx.Params().Len() <= paramIndex { return 0 @@ -281,7 +281,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int32) } }, - reflect.TypeOf(int64(1)): func(paramIndex int) interface{} { + reflect.TypeOf(int64(1)): func(paramIndex int) any { return func(ctx *Context) int64 { if ctx.Params().Len() <= paramIndex { return 0 @@ -289,7 +289,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int64) } }, - reflect.TypeOf(uint(1)): func(paramIndex int) interface{} { + reflect.TypeOf(uint(1)): func(paramIndex int) any { return func(ctx *Context) uint { if ctx.Params().Len() <= paramIndex { return 0 @@ -297,7 +297,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint) } }, - reflect.TypeOf(uint8(1)): func(paramIndex int) interface{} { + reflect.TypeOf(uint8(1)): func(paramIndex int) any { return func(ctx *Context) uint8 { if ctx.Params().Len() <= paramIndex { return 0 @@ -305,7 +305,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint8) } }, - reflect.TypeOf(uint16(1)): func(paramIndex int) interface{} { + reflect.TypeOf(uint16(1)): func(paramIndex int) any { return func(ctx *Context) uint16 { if ctx.Params().Len() <= paramIndex { return 0 @@ -313,7 +313,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint16) } }, - reflect.TypeOf(uint32(1)): func(paramIndex int) interface{} { + reflect.TypeOf(uint32(1)): func(paramIndex int) any { return func(ctx *Context) uint32 { if ctx.Params().Len() <= paramIndex { return 0 @@ -321,7 +321,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint32) } }, - reflect.TypeOf(uint64(1)): func(paramIndex int) interface{} { + reflect.TypeOf(uint64(1)): func(paramIndex int) any { return func(ctx *Context) uint64 { if ctx.Params().Len() <= paramIndex { return 0 @@ -329,7 +329,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint64) } }, - reflect.TypeOf(true): func(paramIndex int) interface{} { + reflect.TypeOf(true): func(paramIndex int) any { return func(ctx *Context) bool { if ctx.Params().Len() <= paramIndex { return false @@ -337,7 +337,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(bool) } }, - reflect.TypeOf(time.Time{}): func(paramIndex int) interface{} { + reflect.TypeOf(time.Time{}): func(paramIndex int) any { return func(ctx *Context) time.Time { if ctx.Params().Len() <= paramIndex { return unixEpochTime @@ -351,7 +351,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ return v } }, - reflect.TypeOf(time.Weekday(0)): func(paramIndex int) interface{} { + reflect.TypeOf(time.Weekday(0)): func(paramIndex int) any { return func(ctx *Context) time.Weekday { if ctx.Params().Len() <= paramIndex { return time.Sunday @@ -382,7 +382,7 @@ func ParamResolverByTypeAndIndex(typ reflect.Type, paramIndex int) (reflect.Valu /* NO: // This could work but its result is not exact type, so direct binding is not possible. resolver := m.ParamResolver - fn := func(ctx *context.Context) interface{} { + fn := func(ctx *context.Context) any { entry, _ := ctx.Params().GetEntry(paramName) return resolver(entry) } diff --git a/context/response_recorder.go b/context/response_recorder.go index 850b6781..617b2cac 100644 --- a/context/response_recorder.go +++ b/context/response_recorder.go @@ -17,7 +17,7 @@ var Recorder = func(ctx *Context) { ctx.Next() } -var rrpool = sync.Pool{New: func() interface{} { return &ResponseRecorder{} }} +var rrpool = sync.Pool{New: func() any { return &ResponseRecorder{} }} // AcquireResponseRecorder returns a new *AcquireResponseRecorder from the pool. // Releasing is done automatically when request and response is done. diff --git a/context/response_writer.go b/context/response_writer.go index 18f88ea3..e4ca8bb3 100644 --- a/context/response_writer.go +++ b/context/response_writer.go @@ -127,7 +127,7 @@ type ResponseWriterWriteTo interface { // | Response Writer Implementation | // +------------------------------------------------------------+ -var rpool = sync.Pool{New: func() interface{} { return &responseWriter{} }} +var rpool = sync.Pool{New: func() any { return &responseWriter{} }} // AcquireResponseWriter returns a new *ResponseWriter from the pool. // Releasing is done automatically when request and response is done. diff --git a/context/route.go b/context/route.go index 4cc4794e..f1a17eb5 100644 --- a/context/route.go +++ b/context/route.go @@ -64,7 +64,7 @@ type RouteReadOnly interface { // Property returns a specific property based on its "key" // of this route's Party owner. - Property(key string) (interface{}, bool) + Property(key string) (any, bool) // Sitemap properties: https://www.sitemaps.org/protocol.html diff --git a/context/view.go b/context/view.go index dcf1bced..3a657d86 100644 --- a/context/view.go +++ b/context/view.go @@ -10,7 +10,7 @@ import ( type ErrViewNotExist struct { Name string IsLayout bool - Data interface{} + Data any } // Error completes the `error` interface. @@ -29,7 +29,7 @@ type ViewEngine interface { // Load should load the templates from the given FileSystem. Load() error // ExecuteWriter should execute a template by its filename with an optional layout and bindingData. - ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error + ExecuteWriter(w io.Writer, filename string, layout string, bindingData any) error // Ext should return the final file extension (including the dot) // which this view engine is responsible to render. // If the filename extension on ExecuteWriter is empty then this is appended. @@ -42,5 +42,5 @@ type ViewEngine interface { // like {{ url }}, {{ urlpath }} and {{ tr }}. type ViewEngineFuncer interface { // AddFunc should adds a function to the template's function map. - AddFunc(funcName string, funcBody interface{}) + AddFunc(funcName string, funcBody any) } diff --git a/core/errgroup/errgroup.go b/core/errgroup/errgroup.go index 1f30cb19..753e8521 100644 --- a/core/errgroup/errgroup.go +++ b/core/errgroup/errgroup.go @@ -21,7 +21,7 @@ func Check(err error) error { // If "err" is *Group then it fires the "visitor" for each of its errors, including children. // if "err" is *Error then it fires the "visitor" with its type and wrapped error. // Otherwise it fires the "visitor" once with typ of nil and err as "err". -func Walk(err error, visitor func(typ interface{}, err error)) error { +func Walk(err error, visitor func(typ any, err error)) error { if err == nil { return nil } @@ -66,7 +66,7 @@ func Errors(err error, conv bool) []error { return []error{err} } -func Type(err error) interface{} { +func Type(err error) any { if err == nil { return nil } @@ -95,8 +95,8 @@ func Fill(parent *Group, errors []*Error) { // It is a special error type which keep the "Type" of the // Group that it's created through Group's `Err` and `Errf` methods. type Error struct { - Err error `json:"error" xml:"Error" yaml:"Error" toml:"Error" sql:"error"` - Type interface{} `json:"type" xml:"Type" yaml:"Type" toml:"Type" sql:"type"` + Err error `json:"error" xml:"Error" yaml:"Error" toml:"Error" sql:"error"` + Type any `json:"type" xml:"Type" yaml:"Type" toml:"Type" sql:"type"` } // Error returns the error message of the "Err". @@ -129,7 +129,7 @@ func (e *Error) Is(err error) bool { } // As reports whether the "target" can be used as &Error{target.Type: ?}. -func (e *Error) As(target interface{}) bool { +func (e *Error) As(target any) bool { if target == nil { return target == e } @@ -157,10 +157,10 @@ func (e *Error) As(target interface{}) bool { type Group struct { parent *Group // a list of children groups, used to get or create new group through Group method. - children map[interface{}]*Group + children map[any]*Group depth int - Type interface{} + Type any Errors []error // []*Error // if true then this Group's Error method will return the messages of the errors made by this Group's Group method. @@ -171,7 +171,7 @@ type Group struct { } // New returns a new empty Group. -func New(typ interface{}) *Group { +func New(typ any) *Group { return &Group{ Type: typ, IncludeChildren: true, @@ -248,9 +248,9 @@ func (g *Group) Unwrap() error { } // Group creates a new group of "typ" type, if does not exist, and returns it. -func (g *Group) Group(typ interface{}) *Group { +func (g *Group) Group(typ any) *Group { if g.children == nil { - g.children = make(map[interface{}]*Group) + g.children = make(map[any]*Group) } else { for _, child := range g.children { if child.Type == typ { @@ -282,7 +282,7 @@ func (g *Group) Add(err error) { } // Addf adds an error to the group like `fmt.Errorf` and returns it. -func (g *Group) Addf(format string, args ...interface{}) error { +func (g *Group) Addf(format string, args ...any) error { err := fmt.Errorf(format, args...) g.Add(err) return err @@ -298,7 +298,7 @@ func (g *Group) Err(err error) error { if !ok { if ge, ok := err.(*Group); ok { if g.children == nil { - g.children = make(map[interface{}]*Group) + g.children = make(map[any]*Group) } g.children[ge.Type] = ge @@ -314,7 +314,7 @@ func (g *Group) Err(err error) error { } // Errf adds an error like `fmt.Errorf` and returns it. -func (g *Group) Errf(format string, args ...interface{}) error { +func (g *Group) Errf(format string, args ...any) error { return g.Err(fmt.Errorf(format, args...)) } diff --git a/core/errgroup/errgroup_test.go b/core/errgroup/errgroup_test.go index bb82a798..e8ea68f6 100644 --- a/core/errgroup/errgroup_test.go +++ b/core/errgroup/errgroup_test.go @@ -145,7 +145,7 @@ func TestGroup(t *testing.T) { t.Run("Walk", func(t *testing.T) { expectedEntries := 4 - _ = Walk(g, func(typ interface{}, err error) { + _ = Walk(g, func(typ any, err error) { g.IncludeChildren = false childAPIErrorsGroup.IncludeChildren = false childAPIErrorsGroup2.IncludeChildren = false diff --git a/core/handlerconv/from_std.go b/core/handlerconv/from_std.go index 18f21911..6f45877e 100644 --- a/core/handlerconv/from_std.go +++ b/core/handlerconv/from_std.go @@ -14,7 +14,7 @@ import ( // .FromStd(h http.Handler) // .FromStd(func(w http.ResponseWriter, r *http.Request)) // .FromStd(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) -func FromStd(handler interface{}) context.Handler { +func FromStd(handler any) context.Handler { switch h := handler.(type) { case context.Handler: return h diff --git a/core/memstore/memstore.go b/core/memstore/memstore.go index 0b71ee75..e4066c9a 100644 --- a/core/memstore/memstore.go +++ b/core/memstore/memstore.go @@ -18,13 +18,13 @@ type ( // ValueSetter is the interface which can be accepted as a generic solution of RequestParams or memstore when Set is the only requirement, // i.e internally on macro/template/TemplateParam#Eval:paramChanger. ValueSetter interface { - Set(key string, newValue interface{}) (Entry, bool) + Set(key string, newValue any) (Entry, bool) } // Entry is the entry of the context storage Store - .Values() Entry struct { - Key string `json:"key" msgpack:"key" yaml:"Key" toml:"Value"` - ValueRaw interface{} `json:"value" msgpack:"value" yaml:"Value" toml:"Value"` - immutable bool // if true then it can't change by its caller. + Key string `json:"key" msgpack:"key" yaml:"Key" toml:"Value"` + ValueRaw any `json:"value" msgpack:"value" yaml:"Value" toml:"Value"` + immutable bool // if true then it can't change by its caller. } // StringEntry is just a key-value wrapped by a struct. @@ -47,7 +47,7 @@ var _ ValueSetter = (*Store)(nil) // // If the "k" kind is not a string or int or int64 or bool // then it will return the raw value of the entry as it's. -func (e Entry) GetByKindOrNil(k reflect.Kind) interface{} { +func (e Entry) GetByKindOrNil(k reflect.Kind) any { switch k { case reflect.String: v := e.StringDefault("__$nf") @@ -136,7 +136,7 @@ func (e *ErrEntryNotFound) Error() string { // Do NOT use this method directly, prefer` errors.As` method as explained above. // // Implements: go/src/errors/wrap.go#84 -func (e *ErrEntryNotFound) As(target interface{}) bool { +func (e *ErrEntryNotFound) As(target any) bool { v, ok := target.(*ErrEntryNotFound) if !ok { return false @@ -721,7 +721,7 @@ func (e Entry) WeekdayDefault(def time.Weekday) (time.Weekday, error) { // Value returns the value of the entry, // respects the immutable. -func (e Entry) Value() interface{} { +func (e Entry) Value() any { if e.immutable { // take its value, no pointer even if set with a reference. vv := reflect.Indirect(reflect.ValueOf(e.ValueRaw)) @@ -751,7 +751,7 @@ func (e Entry) Value() interface{} { // // Returns the entry and true if it was just inserted, meaning that // it will return the entry and a false boolean if the entry exists and it has been updated. -func (r *Store) Save(key string, value interface{}, immutable bool) (Entry, bool) { +func (r *Store) Save(key string, value any, immutable bool) (Entry, bool) { args := *r n := len(args) @@ -802,7 +802,7 @@ func (r *Store) Save(key string, value interface{}, immutable bool) (Entry, bool // it will return the entry and a false boolean if the entry exists and it has been updated. // // See `SetImmutable` and `Get`. -func (r *Store) Set(key string, value interface{}) (Entry, bool) { +func (r *Store) Set(key string, value any) (Entry, bool) { return r.Save(key, value, false) } @@ -817,7 +817,7 @@ func (r *Store) Set(key string, value interface{}) (Entry, bool) { // // Use it consistently, it's far slower than `Set`. // Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081 -func (r *Store) SetImmutable(key string, value interface{}) (Entry, bool) { +func (r *Store) SetImmutable(key string, value any) (Entry, bool) { return r.Save(key, value, true) } @@ -851,7 +851,7 @@ func (r *Store) GetEntryAt(index int) (Entry, bool) { // GetDefault returns the entry's value based on its key. // If not found returns "def". // This function checks for immutability as well, the rest don't. -func (r *Store) GetDefault(key string, def interface{}) interface{} { +func (r *Store) GetDefault(key string, def any) any { v, ok := r.GetEntry(key) if !ok || v.ValueRaw == nil { return def @@ -874,14 +874,14 @@ func (r *Store) Exists(key string) bool { // Get returns the entry's value based on its key. // If not found returns nil. -func (r *Store) Get(key string) interface{} { +func (r *Store) Get(key string) any { return r.GetDefault(key, nil) } // GetOrSet is like `GetDefault` but it accepts a function which is // fired and its result is used to `Set` if // the "key" was not found or its value is nil. -func (r *Store) GetOrSet(key string, setFunc func() interface{}) interface{} { +func (r *Store) GetOrSet(key string, setFunc func() any) any { if v, ok := r.GetEntry(key); ok && v.ValueRaw != nil { return v.Value() } @@ -893,7 +893,7 @@ func (r *Store) GetOrSet(key string, setFunc func() interface{}) interface{} { // Visit accepts a visitor which will be filled // by the key-value objects. -func (r *Store) Visit(visitor func(key string, value interface{})) { +func (r *Store) Visit(visitor func(key string, value any)) { args := *r for i, n := 0, len(args); i < n; i++ { kv := args[i] diff --git a/core/memstore/memstore_test.go b/core/memstore/memstore_test.go index 686d48e4..29ff8caf 100644 --- a/core/memstore/memstore_test.go +++ b/core/memstore/memstore_test.go @@ -150,7 +150,7 @@ func TestJSON(t *testing.T) { expected, got := p.Get(v.Key), v.ValueRaw if ex, g := fmt.Sprintf("%v", expected), fmt.Sprintf("%v", got); ex != g { - if _, isMap := got.(map[string]interface{}); isMap { + if _, isMap := got.(map[string]any); isMap { // was struct but converted into map (as expected). b1, _ := json.Marshal(expected) b2, _ := json.Marshal(got) diff --git a/core/router/api_builder.go b/core/router/api_builder.go index 096fd887..34e33083 100644 --- a/core/router/api_builder.go +++ b/core/router/api_builder.go @@ -360,7 +360,7 @@ func (api *APIBuilder) EnsureStaticBindings() Party { // RegisterDependency calls the `ConfigureContainer.RegisterDependency` method // with the provided value(s). See `HandleFunc` and `PartyConfigure` methods too. -func (api *APIBuilder) RegisterDependency(dependencies ...interface{}) { +func (api *APIBuilder) RegisterDependency(dependencies ...any) { diContainer := api.ConfigureContainer() for i, dependency := range dependencies { if dependency == nil { @@ -442,7 +442,7 @@ func (api *APIBuilder) RegisterDependency(dependencies ...interface{}) { // the dependency injection, mvc and function handlers. // // This method is just a shortcut of the `ConfigureContainer().Handle`. -func (api *APIBuilder) HandleFunc(method, relativePath string, handlersFn ...interface{}) *Route { +func (api *APIBuilder) HandleFunc(method, relativePath string, handlersFn ...any) *Route { return api.ConfigureContainer().Handle(method, relativePath, handlersFn...) } @@ -451,7 +451,7 @@ func (api *APIBuilder) HandleFunc(method, relativePath string, handlersFn ...int // or a result of and/or an error. // // This method is just a shortcut of the `ConfigureContainer().Use`. -func (api *APIBuilder) UseFunc(handlersFn ...interface{}) { +func (api *APIBuilder) UseFunc(handlersFn ...any) { api.ConfigureContainer().Use(handlersFn...) } @@ -636,7 +636,7 @@ func (api *APIBuilder) HandleMany(methodOrMulti string, relativePathorMulti stri // // Examples: // https://github.com/kataras/iris/tree/main/_examples/file-server -func (api *APIBuilder) HandleDir(requestPath string, fsOrDir interface{}, opts ...DirOptions) (routes []*Route) { +func (api *APIBuilder) HandleDir(requestPath string, fsOrDir any, opts ...DirOptions) (routes []*Route) { options := DefaultDirOptions if len(opts) > 0 { options = opts[0] @@ -1401,7 +1401,7 @@ func (api *APIBuilder) MiddlewareExists(handlerNameOrFunc any) bool { // Returns the Party itself for chain calls. // // Should be called before children routes regitration. -func (api *APIBuilder) RemoveHandler(namesOrHandlers ...interface{}) Party { +func (api *APIBuilder) RemoveHandler(namesOrHandlers ...any) Party { var counter *int for _, nameOrHandler := range namesOrHandlers { diff --git a/core/router/api_container.go b/core/router/api_container.go index 0c571fa9..112dbcc8 100644 --- a/core/router/api_container.go +++ b/core/router/api_container.go @@ -20,7 +20,7 @@ type APIContainer struct { // Party returns a child of this `APIContainer` featured with Dependency Injection. // Like the `Self.Party` method does for the common Router Groups. -func (api *APIContainer) Party(relativePath string, handlersFn ...interface{}) *APIContainer { +func (api *APIContainer) Party(relativePath string, handlersFn ...any) *APIContainer { handlers := api.convertHandlerFuncs(relativePath, handlersFn...) p := api.Self.Party(relativePath, handlers...) return p.ConfigureContainer() @@ -67,7 +67,7 @@ func (api *APIContainer) OnError(errorHandler func(*context.Context, error)) { // - RegisterDependency(func(User) OtherResponse {...}) // // See `OnError`, `Use`, `Done` and `Handle` too. -func (api *APIContainer) RegisterDependency(dependency interface{}) *hero.Dependency { +func (api *APIContainer) RegisterDependency(dependency any) *hero.Dependency { return api.Container.Register(dependency) } @@ -117,7 +117,7 @@ func (api *APIContainer) SetDependencyMatcher(fn hero.DependencyMatcher) *APICon } // convertHandlerFuncs accepts Iris hero handlers and returns a slice of native Iris handlers. -func (api *APIContainer) convertHandlerFuncs(relativePath string, handlersFn ...interface{}) context.Handlers { +func (api *APIContainer) convertHandlerFuncs(relativePath string, handlersFn ...any) context.Handlers { fullpath := api.Self.GetRelPath() + relativePath paramsCount := macro.CountParams(fullpath, *api.Self.Macros()) @@ -136,7 +136,7 @@ func (api *APIContainer) convertHandlerFuncs(relativePath string, handlersFn ... return handlers } -func fixRouteInfo(route *Route, handlersFn []interface{}) { +func fixRouteInfo(route *Route, handlersFn []any) { // Fix main handler name and source modified by execution rules wrapper. route.MainHandlerName, route.MainHandlerIndex = context.MainHandlerName(handlersFn...) if len(handlersFn) > route.MainHandlerIndex { @@ -147,7 +147,7 @@ func fixRouteInfo(route *Route, handlersFn []interface{}) { // Handler receives a function which can receive dependencies and output result // and returns a common Iris Handler, useful for Versioning API integration otherwise // the `Handle/Get/Post...` methods are preferable. -func (api *APIContainer) Handler(handlerFn interface{}, handlerParamsCount int) context.Handler { +func (api *APIContainer) Handler(handlerFn any, handlerParamsCount int) context.Handler { paramsCount := macro.CountParams(api.Self.GetRelPath(), *api.Self.Macros()) + handlerParamsCount return api.Container.HandlerWithParams(handlerFn, paramsCount) } @@ -155,14 +155,14 @@ func (api *APIContainer) Handler(handlerFn interface{}, handlerParamsCount int) // Use same as `Self.Use` but it accepts dynamic functions as its "handlersFn" input. // // See `OnError`, `RegisterDependency`, `Done` and `Handle` for more. -func (api *APIContainer) Use(handlersFn ...interface{}) { +func (api *APIContainer) Use(handlersFn ...any) { handlers := api.convertHandlerFuncs("/", handlersFn...) api.Self.Use(handlers...) } // Done same as `Self.Done` but it accepts dynamic functions as its "handlersFn" input. // See `OnError`, `RegisterDependency`, `Use` and `Handle` for more. -func (api *APIContainer) Done(handlersFn ...interface{}) { +func (api *APIContainer) Done(handlersFn ...any) { handlers := api.convertHandlerFuncs("/", handlersFn...) api.Self.Done(handlers...) } @@ -178,7 +178,7 @@ func (api *APIContainer) Done(handlersFn ...interface{}) { // the end-developer should output an error and return `iris.ErrStopExecution`. // // See `OnError`, `RegisterDependency`, `Use`, `Done`, `Get`, `Post`, `Put`, `Patch` and `Delete` too. -func (api *APIContainer) Handle(method, relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Handle(method, relativePath string, handlersFn ...any) *Route { handlers := api.convertHandlerFuncs(relativePath, handlersFn...) route := api.Self.Handle(method, relativePath, handlers...) fixRouteInfo(route, handlersFn) @@ -188,63 +188,63 @@ func (api *APIContainer) Handle(method, relativePath string, handlersFn ...inter // Get registers a route for the Get HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Get(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Get(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodGet, relativePath, handlersFn...) } // Post registers a route for the Post HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Post(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Post(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodPost, relativePath, handlersFn...) } // Put registers a route for the Put HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Put(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Put(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodPut, relativePath, handlersFn...) } // Delete registers a route for the Delete HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Delete(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Delete(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodDelete, relativePath, handlersFn...) } // Connect registers a route for the Connect HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Connect(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Connect(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodConnect, relativePath, handlersFn...) } // Head registers a route for the Head HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Head(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Head(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodHead, relativePath, handlersFn...) } // Options registers a route for the Options HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Options(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Options(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodOptions, relativePath, handlersFn...) } // Patch registers a route for the Patch HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Patch(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Patch(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodPatch, relativePath, handlersFn...) } // Trace registers a route for the Trace HTTP Method. // // Returns a *Route and an error which will be filled if route wasn't registered successfully. -func (api *APIContainer) Trace(relativePath string, handlersFn ...interface{}) *Route { +func (api *APIContainer) Trace(relativePath string, handlersFn ...any) *Route { return api.Handle(http.MethodTrace, relativePath, handlersFn...) } @@ -258,7 +258,7 @@ func (api *APIContainer) Trace(relativePath string, handlersFn ...interface{}) * // Options // Connect // Trace -func (api *APIContainer) Any(relativePath string, handlersFn ...interface{}) (routes []*Route) { +func (api *APIContainer) Any(relativePath string, handlersFn ...any) (routes []*Route) { handlers := api.convertHandlerFuncs(relativePath, handlersFn...) for _, m := range AllMethods { @@ -274,7 +274,7 @@ func (api *APIContainer) Any(relativePath string, handlersFn ...interface{}) (ro // OnErrorCode registers a handlers chain for this `Party` for a specific HTTP status code. // Read more at: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml // Look `OnAnyErrorCode` too. -func (api *APIContainer) OnErrorCode(statusCode int, handlersFn ...interface{}) []*Route { +func (api *APIContainer) OnErrorCode(statusCode int, handlersFn ...any) []*Route { handlers := api.convertHandlerFuncs("/{tail:path}", handlersFn...) return api.Self.OnErrorCode(statusCode, handlers...) } @@ -282,7 +282,7 @@ func (api *APIContainer) OnErrorCode(statusCode int, handlersFn ...interface{}) // OnAnyErrorCode registers a handlers chain for all error codes // (4xxx and 5xxx, change the `ClientErrorCodes` and `ServerErrorCodes` variables to modify those) // Look `OnErrorCode` too. -func (api *APIContainer) OnAnyErrorCode(handlersFn ...interface{}) []*Route { +func (api *APIContainer) OnAnyErrorCode(handlersFn ...any) []*Route { handlers := api.convertHandlerFuncs("/{tail:path}", handlersFn...) return api.Self.OnAnyErrorCode(handlers...) } diff --git a/core/router/fs.go b/core/router/fs.go index 2bacd5f8..22b6b62c 100644 --- a/core/router/fs.go +++ b/core/router/fs.go @@ -1199,7 +1199,7 @@ func (fi *fileInfo) Mode() os.FileMode { return fi.mode } func (fi *fileInfo) ModTime() time.Time { return fi.modTime } func (fi *fileInfo) IsDir() bool { return fi.isDir } func (fi *fileInfo) Size() int64 { return 0 } -func (fi *fileInfo) Sys() interface{} { return fi } +func (fi *fileInfo) Sys() any { return fi } type dir struct { os.FileInfo // *fileInfo diff --git a/core/router/party.go b/core/router/party.go index 1fbc538f..f4ae9cb8 100644 --- a/core/router/party.go +++ b/core/router/party.go @@ -33,7 +33,7 @@ type Party interface { EnsureStaticBindings() Party // RegisterDependency calls the `ConfigureContainer.RegisterDependency` method // with the provided value(s). See `HandleFunc` and `PartyConfigure` methods too. - RegisterDependency(dependencies ...interface{}) + RegisterDependency(dependencies ...any) // HandleFunc registers a route on HTTP verb "method" and relative, to this Party, path. // It is like the `Handle` method but it accepts one or more "handlersFn" functions // that each one of them can accept any input arguments as the HTTP request and @@ -103,13 +103,13 @@ type Party interface { // the dependency injection, mvc and function handlers. // // This method is just a shortcut for the `ConfigureContainer().Handle` one. - HandleFunc(method, relativePath string, handlersFn ...interface{}) *Route + HandleFunc(method, relativePath string, handlersFn ...any) *Route // UseFunc registers a function which can accept one or more // dependencies (see RegisterDependency) and returns an iris.Handler // or a result of and/or an error. // // This method is just a shortcut of the `ConfigureContainer().Use`. - UseFunc(handlersFn ...interface{}) + UseFunc(handlersFn ...any) // GetRelPath returns the current party's relative path. // i.e: @@ -245,7 +245,7 @@ type Party interface { // Returns the Party itself for chain calls. // // Should be called before children routes regitration. - RemoveHandler(namesOrHandlers ...interface{}) Party + RemoveHandler(namesOrHandlers ...any) Party // Reset removes all the begin and done handlers that may derived from the parent party via `Use` & `Done`, // and the execution rules. // Note that the `Reset` will not reset the handlers that are registered via `UseGlobal` & `DoneGlobal`. @@ -338,7 +338,7 @@ type Party interface { // // Examples: // https://github.com/kataras/iris/tree/main/_examples/file-server - HandleDir(requestPath string, fileSystem interface{}, opts ...DirOptions) []*Route + HandleDir(requestPath string, fileSystem any, opts ...DirOptions) []*Route // None registers an "offline" route // see context.ExecRoute(routeName) and diff --git a/core/router/path.go b/core/router/path.go index 1936057a..b79d0c6f 100644 --- a/core/router/path.go +++ b/core/router/path.go @@ -335,7 +335,7 @@ func NewRoutePathReverser(apiRoutesProvider RoutesProvider, options ...RoutePath } // Path returns a route path based on a route name and any dynamic named parameter's values-only. -func (ps *RoutePathReverser) Path(routeName string, paramValues ...interface{}) string { +func (ps *RoutePathReverser) Path(routeName string, paramValues ...any) string { r := ps.provider.GetRoute(routeName) if r == nil { return "" @@ -348,7 +348,7 @@ func (ps *RoutePathReverser) Path(routeName string, paramValues ...interface{}) return r.ResolvePath(toStringSlice(paramValues)...) } -func toStringSlice(args []interface{}) (argsString []string) { +func toStringSlice(args []any) (argsString []string) { argsSize := len(args) if argsSize <= 0 { return @@ -376,7 +376,7 @@ func toStringSlice(args []interface{}) (argsString []string) { // developers can just concat the subdomain, (host can be auto-retrieve by browser using the Path). // URL same as Path but returns the full uri, i.e https://mysubdomain.mydomain.com/hello/iris -func (ps *RoutePathReverser) URL(routeName string, paramValues ...interface{}) (url string) { +func (ps *RoutePathReverser) URL(routeName string, paramValues ...any) (url string) { if ps.vhost == "" || ps.vscheme == "" { return "not supported" } diff --git a/core/router/route.go b/core/router/route.go index 9caa6f15..3080a5c0 100644 --- a/core/router/route.go +++ b/core/router/route.go @@ -154,7 +154,7 @@ func (r *Route) UseOnce(handlers ...context.Handler) { // Returns the total amount of handlers removed. // // Should be called before Application Build. -func (r *Route) RemoveHandler(namesOrHandlers ...interface{}) (count int) { +func (r *Route) RemoveHandler(namesOrHandlers ...any) (count int) { for _, nameOrHandler := range namesOrHandlers { handlerName := "" switch h := nameOrHandler.(type) { @@ -644,7 +644,7 @@ func (rd routeReadOnlyWrapper) MainHandlerIndex() int { return rd.Route.MainHandlerIndex } -func (rd routeReadOnlyWrapper) Property(key string) (interface{}, bool) { +func (rd routeReadOnlyWrapper) Property(key string) (any, bool) { properties := rd.Route.Party.Properties() if properties != nil { if property, ok := properties[key]; ok { diff --git a/hero/container_test.go b/hero/container_test.go index f0e35098..20eaf454 100644 --- a/hero/container_test.go +++ b/hero/container_test.go @@ -101,16 +101,16 @@ func TestContainerInject(t *testing.T) { func TestContainerUseResultHandler(t *testing.T) { c := New() resultLogger := func(next ResultHandler) ResultHandler { - return func(ctx iris.Context, v interface{}) error { + return func(ctx iris.Context, v any) error { t.Logf("%#+v", v) return next(ctx, v) } } c.UseResultHandler(resultLogger) - expectedResponse := map[string]interface{}{"injected": true} + expectedResponse := map[string]any{"injected": true} c.UseResultHandler(func(next ResultHandler) ResultHandler { - return func(ctx iris.Context, v interface{}) error { + return func(ctx iris.Context, v any) error { return next(ctx, expectedResponse) } }) diff --git a/hero/dependency.go b/hero/dependency.go index d7aa7d4c..c83a7f36 100644 --- a/hero/dependency.go +++ b/hero/dependency.go @@ -24,7 +24,7 @@ type ( // Contains its source location, the dependency handler (provider) itself and information // such as static for static struct values or explicit to bind a value to its exact DestType and not if just assignable to it (interfaces). Dependency struct { - OriginalValue interface{} // Used for debugging and for logging only. + OriginalValue any // Used for debugging and for logging only. Source Source Handle DependencyHandler // It's the exact type of return to bind, if declared to return , otherwise nil. @@ -75,12 +75,12 @@ func (d *Dependency) String() string { // NewDependency converts a function or a function which accepts other dependencies or static struct value to a *Dependency. // // See `Container.Handler` for more. -func NewDependency(dependency interface{}, funcDependencies ...*Dependency) *Dependency { // used only on tests. +func NewDependency(dependency any, funcDependencies ...*Dependency) *Dependency { // used only on tests. return newDependency(dependency, false, false, nil, funcDependencies...) } func newDependency( - dependency interface{}, + dependency any, disablePayloadAutoBinding bool, enableStructDependents bool, matchDependency DependencyMatcher, diff --git a/hero/dependency_test.go b/hero/dependency_test.go index a3edcba6..003c516a 100644 --- a/hero/dependency_test.go +++ b/hero/dependency_test.go @@ -11,8 +11,8 @@ import ( ) type testDependencyTest struct { - Dependency interface{} - Expected interface{} + Dependency any + Expected any } func TestDependency(t *testing.T) { @@ -66,14 +66,14 @@ func TestDependency(t *testing.T) { }, { - Dependency: func(*context.Context) interface{} { + Dependency: func(*context.Context) any { return "1" }, Expected: "1", }, { - Dependency: func(*context.Context) interface{} { + Dependency: func(*context.Context) any { return false }, Expected: false, diff --git a/hero/func_result.go b/hero/func_result.go index f213f09f..a527e971 100644 --- a/hero/func_result.go +++ b/hero/func_result.go @@ -11,9 +11,9 @@ import ( ) // ResultHandler describes the function type which should serve the "v" struct value. -type ResultHandler func(ctx *context.Context, v interface{}) error +type ResultHandler func(ctx *context.Context, v any) error -func defaultResultHandler(ctx *context.Context, v interface{}) error { +func defaultResultHandler(ctx *context.Context, v any) error { if p, ok := v.(PreflightResult); ok { if err := p.Preflight(ctx); err != nil { return err @@ -183,7 +183,7 @@ func dispatchFuncResult(ctx *context.Context, values []reflect.Value, handler Re // if not nil then check // for content type (or json default) and send the custom data object // except when found == false or err != nil. - custom interface{} + custom any // if false then skip everything and fire 404. found = true // defaults to true of course, otherwise will break :) ) @@ -334,7 +334,7 @@ func dispatchFuncResult(ctx *context.Context, values []reflect.Value, handler Re // dispatchCommon is being used internally to send // commonly used data to the response writer with a smart way. func dispatchCommon(ctx *context.Context, - statusCode int, contentType string, content []byte, v interface{}, handler ResultHandler, found bool) error { + statusCode int, contentType string, content []byte, v any, handler ResultHandler, found bool) error { // if we have a false boolean as a return value // then skip everything and fire a not found, // we even don't care about the given status code or the object or the content. @@ -396,7 +396,7 @@ type Response struct { // previously set "ContentType". If "Lang" and "Text" are not empty // then this "Object" field becomes the template data that the // locale text should use to be rendered. - Object interface{} + Object any // If Path is not empty then it will redirect // the client to this Path, if Code is >= 300 and < 400 @@ -469,7 +469,7 @@ func (r Response) Dispatch(ctx *context.Context) { type View struct { Name string Layout string - Data interface{} // map or a custom struct. + Data any // map or a custom struct. Code int Err error } @@ -502,7 +502,7 @@ func (r View) Dispatch(ctx *context.Context) { // r as Response view. } else { // else check if r.Data is map or struct, if struct convert it to map, // do a range loop and modify the data one by one. - // context.Map is actually a map[string]interface{} but we have to make that check: + // context.Map is actually a map[string]any but we have to make that check: if m, ok := r.Data.(context.Map); ok { setViewData(ctx, m) } else if reflect.Indirect(reflect.ValueOf(r.Data)).Kind() == reflect.Struct { @@ -515,7 +515,7 @@ func (r View) Dispatch(ctx *context.Context) { // r as Response view. } } -func setViewData(ctx *context.Context, data map[string]interface{}) { +func setViewData(ctx *context.Context, data map[string]any) { for k, v := range data { ctx.ViewData(k, v) } diff --git a/hero/func_result_test.go b/hero/func_result_test.go index 39798a2f..5d674dea 100644 --- a/hero/func_result_test.go +++ b/hero/func_result_test.go @@ -107,7 +107,7 @@ func GetCustomTypedPtrNilEmptyResponse() *iris.Map { return nil } -func GetCustomMapNilEmptyResponse() map[string]interface{} { +func GetCustomMapNilEmptyResponse() map[string]any { return nil } @@ -172,7 +172,7 @@ func TestFuncResult(t *testing.T) { ContentType("text/html", "utf-8"). Body().IsEqual("internal server error") - expectedResultFromCustomStruct := map[string]interface{}{ + expectedResultFromCustomStruct := map[string]any{ "name": "Iris", "age": 2, } diff --git a/hero/handler.go b/hero/handler.go index 3a31e9f4..b83e0c15 100644 --- a/hero/handler.go +++ b/hero/handler.go @@ -93,7 +93,7 @@ func isIrisHandlerType(typ reflect.Type) bool { return typ == irisHandlerType || typ == irisHandlerFuncType } -func makeHandler(fn interface{}, c *Container, paramsCount int) context.Handler { +func makeHandler(fn any, c *Container, paramsCount int) context.Handler { if fn == nil { panic("makeHandler: function is nil") } @@ -184,7 +184,7 @@ func makeHandler(fn interface{}, c *Container, paramsCount int) context.Handler } } -func isHandler(fn interface{}) (context.Handler, bool) { +func isHandler(fn any) (context.Handler, bool) { if handler, ok := fn.(context.Handler); ok { return handler, ok } @@ -196,7 +196,7 @@ func isHandler(fn interface{}) (context.Handler, bool) { return nil, false } -func isHandlerWithError(fn interface{}) (func(*context.Context) error, bool) { +func isHandlerWithError(fn any) (func(*context.Context) error, bool) { if handlerWithErr, ok := fn.(func(*context.Context) error); ok { return handlerWithErr, true } diff --git a/hero/reflect.go b/hero/reflect.go index c54d398f..85e4c372 100644 --- a/hero/reflect.go +++ b/hero/reflect.go @@ -7,7 +7,7 @@ import ( "github.com/kataras/iris/v12/context" ) -func valueOf(v interface{}) reflect.Value { +func valueOf(v any) reflect.Value { if val, ok := v.(reflect.Value); ok { // check if it's already a reflect.Value. return val @@ -124,7 +124,7 @@ func equalTypes(binding reflect.Type, input reflect.Type) bool { return binding.AssignableTo(input) } - // dependency: func(...) interface{} { return "string" } + // dependency: func(...) any { return "string" } // expected input: string. if binding.Kind() == reflect.Interface { return input.AssignableTo(binding) diff --git a/hero/struct.go b/hero/struct.go index b6bedcbf..a243885e 100644 --- a/hero/struct.go +++ b/hero/struct.go @@ -55,7 +55,7 @@ func isMarkedAsSingleton(structPtr any) bool { return false } -func makeStruct(structPtr interface{}, c *Container, partyParamsCount int) *Struct { +func makeStruct(structPtr any, c *Container, partyParamsCount int) *Struct { v := valueOf(structPtr) typ := v.Type() if typ.Kind() != reflect.Ptr || indirectType(typ).Kind() != reflect.Struct {