1
0
mirror of https://github.com/kataras/iris.git synced 2026-06-10 07:33:42 +00:00

CI: minor: use the new exclude-paths (dependabot PR approved some days ago)

This commit is contained in:
Gerasimos (Makis) Maropoulos
2025-08-16 22:48:38 +03:00
parent a8a3afea22
commit 92164cee52
37 changed files with 268 additions and 266 deletions
+4 -2
View File
@@ -2,9 +2,11 @@ version: 2
updates: updates:
- package-ecosystem: "gomod" - package-ecosystem: "gomod"
directory: "/" directory: "/"
exclude-paths:
- "_examples/"
schedule: schedule:
interval: "weekly" interval: "monthly"
- package-ecosystem: "github-actions" - package-ecosystem: "github-actions"
directory: "/" directory: "/"
schedule: schedule:
interval: "weekly" interval: "monthly"
+1 -1
View File
@@ -19,7 +19,7 @@ type (
Pattern string Pattern string
// Target is the target Host that incoming requests will be redirected on pattern match // 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. // 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. // Hosts is a switch provider.
// It can be used as input argument to the `Switch` function // It can be used as input argument to the `Switch` function
+2 -2
View File
@@ -30,7 +30,7 @@ type Application interface {
// Validate validates a value and returns nil if passed or // Validate validates a value and returns nil if passed or
// the failure reason if not. // the failure reason if not.
Validate(interface{}) error Validate(any) error
// Minifier returns the minifier instance. // Minifier returns the minifier instance.
// By default it can minifies: // By default it can minifies:
@@ -44,7 +44,7 @@ type Application interface {
// //
// Use context.View to render templates to the client instead. // Use context.View to render templates to the client instead.
// Returns an error on failure, otherwise nil. // 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. // 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. // Iris automatically releases the request context, so you don't have to use it.
+1 -1
View File
@@ -170,7 +170,7 @@ func NewCompressReader(src io.Reader, encoding string) (*CompressReader, error)
}, nil }, 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" // AddCompressHeaders just adds the headers "Vary" to "Accept-Encoding"
// and "Content-Encoding" to the given encoding. // and "Content-Encoding" to the given encoding.
+1 -1
View File
@@ -96,5 +96,5 @@ type ConfigurationReadOnly interface {
// GetHostProxyHeaders returns the HostProxyHeaders field. // GetHostProxyHeaders returns the HostProxyHeaders field.
GetHostProxyHeaders() map[string]bool GetHostProxyHeaders() map[string]bool
// GetOther returns the Other field. // GetOther returns the Other field.
GetOther() map[string]interface{} GetOther() map[string]any
} }
+97 -97
View File
@@ -84,7 +84,7 @@ type (
// Unmarshaler is the interface implemented by types that can unmarshal any raw data. // 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. // TIP INFO: Any pointer to a value which implements the BodyDecoder can be override the unmarshaler.
Unmarshaler interface { Unmarshaler interface {
Unmarshal(data []byte, outPtr interface{}) error Unmarshal(data []byte, outPtr any) error
} }
// UnmarshalerFunc a shortcut for the Unmarshaler interface // UnmarshalerFunc a shortcut for the Unmarshaler interface
@@ -92,20 +92,20 @@ type (
// See 'Unmarshaler' and 'BodyDecoder' for more. // See 'Unmarshaler' and 'BodyDecoder' for more.
// //
// Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-custom-via-unmarshaler/main.go // 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. // DecodeFunc is a generic type of decoder function.
// When the returned error is not nil the decode operation // When the returned error is not nil the decode operation
// is terminated and the error is received by the ReadJSONStream method, // is terminated and the error is received by the ReadJSONStream method,
// otherwise it continues to read the next available object. // otherwise it continues to read the next available object.
// Look the `Context.ReadJSONStream` method. // 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 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, // Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps,
// slices, and pointers as necessary. // 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) 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. // Map is just a type alias of the map[string]any type.
type Map = map[string]interface{} type Map = map[string]any
// Context is the midle-man server's "object" dealing with incoming requests. // Context is the midle-man server's "object" dealing with incoming requests.
// //
@@ -433,7 +433,7 @@ type goroutines struct {
mu sync.RWMutex mu sync.RWMutex
} }
var acquireGoroutines = func() interface{} { var acquireGoroutines = func() any {
return &goroutines{wg: new(sync.WaitGroup)} 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 // If the status code is a failure one then
// it will also fire the specified error code handler. // 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) ctx.StopWithStatus(statusCode)
return ctx.writeJSON(jsonObject, &DefaultJSONOptions) // do not modify - see errors.DefaultContextErrorHandler. return ctx.writeJSON(jsonObject, &DefaultJSONOptions) // do not modify - see errors.DefaultContextErrorHandler.
} }
@@ -1359,7 +1359,7 @@ func (ctx *Context) GetLocale() Locale {
// See `GetLocale` too. // See `GetLocale` too.
// //
// Example: https://github.com/kataras/iris/tree/main/_examples/i18n // 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...) 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 // Validator is the validator for request body on Context methods such as
// ReadJSON, ReadMsgPack, ReadXML, ReadYAML, ReadForm, ReadQuery, ReadBody and e.t.c. // ReadJSON, ReadMsgPack, ReadXML, ReadYAML, ReadForm, ReadQuery, ReadBody and e.t.c.
type Validator interface { 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 // 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 // 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 // UnmarshalBody reads the request's body and binds it to a value or pointer of any type
// Examples of usage: context.ReadJSON, context.ReadXML. // Examples of usage: context.ReadJSON, context.ReadXML.
// //
// Example: https://github.com/kataras/iris/blob/main/_examples/request-body/read-custom-via-unmarshaler/main.go // 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 { if ctx.request.Body == nil {
return fmt.Errorf("unmarshal: empty body: %w", ErrNotFound) 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 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 var body io.Reader
if ctx.IsRecordingBody() { 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. // 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 // 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...) 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. // 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 // 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)) return ctx.UnmarshalBody(outPtr, UnmarshalerFunc(xml.Unmarshal))
} }
// ReadYAML reads YAML from request's body and binds it to the "outPtr" value. // 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 // 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)) 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. // 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 // 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() values := ctx.FormValues()
if len(values) == 0 { if len(values) == 0 {
if ctx.app.ConfigurationReadOnly().GetFireEmptyFormError() { 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". // 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 // 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() values := ctx.getQuery()
if len(values) == 0 { if len(values) == 0 {
if ctx.app.ConfigurationReadOnly().GetFireEmptyFormError() { 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". // 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 // 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) err := schema.DecodeHeaders(ctx.request.Header, ptr)
if err != nil { if err != nil {
return err 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". // 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 // 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() n := ctx.params.Len()
if n == 0 { if n == 0 {
return nil return nil
@@ -3183,7 +3183,7 @@ func (ctx *Context) ReadParams(ptr interface{}) error {
// to the "ptr" pointer struct value. // to the "ptr" pointer struct value.
// The struct fields may contain "url" or "param" binding tags. // The struct fields may contain "url" or "param" binding tags.
// If a validator exists then it validates the result too. // 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()) values := make(map[string][]string, ctx.params.Len())
ctx.params.Visit(func(key string, value string) { ctx.params.Visit(func(key string, value string) {
values[key] = strings.Split(value, "/") 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. // 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() rawData, err := ctx.GetBody()
if err != nil { if err != nil {
return err 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". // 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 // 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. // 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. // If the ptr is string or byte, read the body as it's.
switch v := ptr.(type) { switch v := ptr.(type) {
case *string: 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. // Writef formats according to a format specifier and writes to the response.
// //
// Returns the number of bytes written and any write error encountered. // 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 { /* if len(a) == 0 {
return ctx.WriteString(format) return ctx.WriteString(format)
} ^ No, let it complain about arguments, because go test will do even if the app is running. } ^ 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. // Look .ViewLayout and .View too.
// //
// Example: https://github.com/kataras/iris/tree/main/_examples/view/context-view-data/ // 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() viewDataContextKey := ctx.app.ConfigurationReadOnly().GetViewDataContextKey()
if key == "" { if key == "" {
ctx.values.Set(viewDataContextKey, value) 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`. // 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 // 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 // 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 // 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 // Similarly to `viewData := ctx.Values().Get("iris.view.data")` or
// `viewData := ctx.Values().Get(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey())`. // `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 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 { if viewData, ok := v.(Map); ok {
return viewData return viewData
} }
// if struct, convert it to map[string]interface{} // if struct, convert it to map[string]any
if structs.IsStruct(v) { if structs.IsStruct(v) {
return structs.Map(v) return structs.Map(v)
} }
@@ -3936,7 +3936,7 @@ func (ctx *Context) FallbackView(providers ...FallbackViewProvider) {
// Look .ViewData and .ViewLayout too. // Look .ViewData and .ViewLayout too.
// //
// Examples: https://github.com/kataras/iris/tree/main/_examples/view // 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) ctx.ContentType(ContentHTMLHeaderValue)
err := ctx.renderView(filename, optionalViewModel...) err := ctx.renderView(filename, optionalViewModel...)
@@ -3959,11 +3959,11 @@ func (ctx *Context) View(filename string, optionalViewModel ...interface{}) erro
return err return err
} }
func (ctx *Context) renderView(filename string, optionalViewModel ...interface{}) error { func (ctx *Context) renderView(filename string, optionalViewModel ...any) error {
cfg := ctx.app.ConfigurationReadOnly() cfg := ctx.app.ConfigurationReadOnly()
layout := ctx.values.GetString(cfg.GetViewLayoutContextKey()) 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 */ { 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`. // a nil can override the existing data or model sent by `ViewData`.
bindingData = optionalViewModel[0] bindingData = optionalViewModel[0]
@@ -4124,7 +4124,7 @@ var (
secureJSONPrefix = []byte("while(1);") 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 ctx.app.ConfigurationReadOnly().GetEnableProtoJSON() {
if m, ok := v.(proto.Message); ok { if m, ok := v.(proto.Message); ok {
protoJSON := ProtoMarshalOptions{} 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'. // 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 == "" { if !options.Secure && !options.ASCII && options.Prefix == "" {
// jsoniterConfig := jsoniter.Config{ // jsoniterConfig := jsoniter.Config{
// EscapeHTML: !options.UnescapeHTML, // EscapeHTML: !options.UnescapeHTML,
@@ -4343,7 +4343,7 @@ func (ctx *Context) RenderComponent(component Component) error {
// //
// Customize the behavior of every `Context.JSON“ can be achieved // Customize the behavior of every `Context.JSON“ can be achieved
// by modifying the package-level `WriteJSON` function on program initilization. // 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 var options *JSON
if len(opts) > 0 { if len(opts) > 0 {
options = &opts[0] options = &opts[0]
@@ -4363,7 +4363,7 @@ func (ctx *Context) JSON(v interface{}, opts ...JSON) (err error) {
return return
} }
func (ctx *Context) writeJSON(v interface{}, options *JSON) error { func (ctx *Context) writeJSON(v any, options *JSON) error {
ctx.ContentType(ContentJSONHeaderValue) ctx.ContentType(ContentJSONHeaderValue)
// After content type given and before everything else, try handle proto or easyjson, no matter the performance mode. // 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(");") var finishCallbackB = []byte(");")
// WriteJSONP marshals the given interface object and writes the JSONP response to the writer. // 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 != "" { if callback := options.Callback; callback != "" {
_, err = ctx.Write(stringToBytes(callback + "(")) _, err = ctx.Write(stringToBytes(callback + "("))
if err != nil { if err != nil {
@@ -4406,7 +4406,7 @@ var DefaultJSONPOptions = JSONP{}
// It reports any JSON parser or write errors back to the caller. // It reports any JSON parser or write errors back to the caller.
// Look the Application.SetContextErrorHandler to override the // Look the Application.SetContextErrorHandler to override the
// default status code 500 with a custom error response. // 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 var options *JSONP
if len(opts) > 0 { if len(opts) > 0 {
options = &opts[0] options = &opts[0]
@@ -4426,13 +4426,13 @@ func (ctx *Context) JSONP(v interface{}, opts ...JSONP) (err error) {
type xmlMapEntry struct { type xmlMapEntry struct {
XMLName xml.Name 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. // 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 { func XMLMap(elementName string, v Map) xml.Marshaler {
return xmlMap{ return xmlMap{
entries: v, 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. // 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 != "" { if prefix := options.Prefix; prefix != "" {
_, err := ctx.Write(stringToBytes(prefix)) _, err := ctx.Write(stringToBytes(prefix))
if err != nil { if err != nil {
@@ -4495,7 +4495,7 @@ var DefaultXMLOptions = XML{}
// It reports any XML parser or write errors back to the caller. // It reports any XML parser or write errors back to the caller.
// Look the Application.SetContextErrorHandler to override the // Look the Application.SetContextErrorHandler to override the
// default status code 500 with a custom error response. // 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 var options *XML
if len(opts) > 0 { if len(opts) > 0 {
options = &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. // send a response of content type "application/problem+xml" instead.
// //
// Read more at: https://github.com/kataras/iris/blob/main/_examples/routing/http-errors. // 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 options := DefaultProblemOptions
if len(opts) > 0 { if len(opts) > 0 {
options = 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. // 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 := yaml.NewEncoder(ctx.writer)
encoder.SetIndent(indentSpace) 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. // It reports any YAML parser or write errors back to the caller.
// Look the Application.SetContextErrorHandler to override the // Look the Application.SetContextErrorHandler to override the
// default status code 500 with a custom error response. // 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) ctx.ContentType(ContentYAMLHeaderValue)
err := WriteYAML(ctx, v, 0) 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. // 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) ctx.ContentType(ContentYAMLTextHeaderValue)
err := WriteYAML(ctx, v, 4) 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. // It reports any message pack or write errors back to the caller.
// Look the Application.SetContextErrorHandler to override the // Look the Application.SetContextErrorHandler to override the
// default status code 500 with a custom error response. // 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) out, err := msgpack.Marshal(v)
if err != nil { if err != nil {
ctx.handleContextError(err) ctx.handleContextError(err)
@@ -4702,7 +4702,7 @@ var ErrContentNotSupported = errors.New("unsupported content")
// //
// See the `N` struct too. // See the `N` struct too.
type ContentSelector interface { type ContentSelector interface {
SelectContent(mime string) interface{} SelectContent(mime string) any
} }
// ContentNegotiator is the interface which structs can implement // ContentNegotiator is the interface which structs can implement
@@ -4732,13 +4732,13 @@ type N struct {
Markdown []byte Markdown []byte
Binary []byte Binary []byte
JSON interface{} JSON any
Problem Problem Problem Problem
JSONP interface{} JSONP any
XML interface{} XML any
YAML interface{} YAML any
Protobuf interface{} Protobuf any
MsgPack interface{} MsgPack any
Other []byte // custom content types. Other []byte // custom content types.
} }
@@ -4746,7 +4746,7 @@ type N struct {
var _ ContentSelector = N{} var _ ContentSelector = N{}
// SelectContent returns a content based on the matched negotiated "mime". // 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 { switch mime {
case ContentTextHeaderValue: case ContentTextHeaderValue:
return n.Text return n.Text
@@ -4842,7 +4842,7 @@ func parseHeader(headerValue string) []string {
// Supports the above without quality values. // Supports the above without quality values.
// //
// Read more at: https://github.com/kataras/iris/tree/main/_examples/response-writer/content-negotiation // 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() contentType, charset, encoding, content := ctx.Negotiation().Build()
if v == nil { if v == nil {
v = content v = content
@@ -4978,7 +4978,7 @@ type NegotiationBuilder struct {
Accept NegotiationAcceptBuilder Accept NegotiationAcceptBuilder
mime []string // we need order. mime []string // we need order.
contents map[string]interface{} // map to the "mime" and content should be rendered if that mime requested. contents map[string]any // map to the "mime" and content should be rendered if that mime requested.
charset []string charset []string
encoding []string encoding []string
} }
@@ -4987,7 +4987,7 @@ type NegotiationBuilder struct {
// through `Context.Negotiate` when this mime type is accepted by client. // through `Context.Negotiate` when this mime type is accepted by client.
// //
// Returns itself for recursive calls. // 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 ",". mimes := parseHeader(mime) // if contains more than one sep by commas ",".
if content == nil { if content == nil {
n.mime = append(n.mime, mimes...) n.mime = append(n.mime, mimes...)
@@ -4995,7 +4995,7 @@ func (n *NegotiationBuilder) MIME(mime string, content interface{}) *Negotiation
} }
if n.contents == nil { if n.contents == nil {
n.contents = make(map[string]interface{}) n.contents = make(map[string]any)
} }
for _, m := range mimes { for _, m := range mimes {
@@ -5012,7 +5012,7 @@ func (n *NegotiationBuilder) MIME(mime string, content interface{}) *Negotiation
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder { func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = v[0] content = v[0]
} }
@@ -5025,7 +5025,7 @@ func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder {
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) HTML(v ...string) *NegotiationBuilder { func (n *NegotiationBuilder) HTML(v ...string) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = v[0] content = v[0]
} }
@@ -5038,7 +5038,7 @@ func (n *NegotiationBuilder) HTML(v ...string) *NegotiationBuilder {
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) Markdown(v ...[]byte) *NegotiationBuilder { func (n *NegotiationBuilder) Markdown(v ...[]byte) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = v content = v
} }
@@ -5051,7 +5051,7 @@ func (n *NegotiationBuilder) Markdown(v ...[]byte) *NegotiationBuilder {
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) Binary(v ...[]byte) *NegotiationBuilder { func (n *NegotiationBuilder) Binary(v ...[]byte) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // when a client accepts the "application/json" content type.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) JSON(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) JSON(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // when a client accepts the "application/problem+json" or the "application/problem+xml" content type.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) Problem(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) Problem(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // when a client accepts the "javascript/javascript" content type.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) JSONP(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) JSONP(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // when a client accepts one of the "text/xml" or "application/xml" content types.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) XML(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) XML(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // when a client accepts the "application/x-yaml" content type.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) YAML(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) YAML(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // when a client accepts the "application/x-yaml" content type.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) TextYAML(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) TextYAML(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // when a client accepts the "application/x-protobuf" content type.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) Protobuf(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) Protobuf(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // when a client accepts one of the "application/x-msgpack" or "application/msgpack" content types.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) MsgPack(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) MsgPack(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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. // Any registers a wildcard that can match any client's accept content type.
// //
// Returns itself for recursive calls. // Returns itself for recursive calls.
func (n *NegotiationBuilder) Any(v ...interface{}) *NegotiationBuilder { func (n *NegotiationBuilder) Any(v ...any) *NegotiationBuilder {
var content interface{} var content any
if len(v) > 0 { if len(v) > 0 {
content = 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, // 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. // 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) contentType = negotiationMatch(n.Accept.accept, n.mime)
charset = negotiationMatch(n.Accept.charset, n.charset) charset = negotiationMatch(n.Accept.charset, n.charset)
encoding = negotiationMatch(n.Accept.encoding, n.encoding) 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. // You either need to provide exactly that amount or you derive the key from what you type in.
// //
// See `Decode` too. // See `Decode` too.
Encode(cookieName string, cookieValue interface{}) (string, error) Encode(cookieName string, cookieValue any) (string, error)
// Decode should decode the cookie value. // Decode should decode the cookie value.
// Should accept the cookie's name as its first argument, // 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. // 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. // You either need to provide exactly that amount or you derive the key from what you type in.
// //
// See `Encode` too. // 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. // 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. // in sake of minimum performance cost.
// //
// See `UnregisterDependency` too. // See `UnregisterDependency` too.
func (ctx *Context) RegisterDependency(v interface{}) { func (ctx *Context) RegisterDependency(v any) {
if v == nil { if v == nil {
return return
} }
@@ -6350,7 +6350,7 @@ func (ctx *Context) GetErrPublic() (bool, error) {
// which recovers from a manual panic. // which recovers from a manual panic.
type ErrPanicRecovery struct { type ErrPanicRecovery struct {
ErrPrivate ErrPrivate
Cause interface{} Cause any
Callers []string // file:line callers. Callers []string // file:line callers.
Stack []byte // the full debug stack. Stack []byte // the full debug stack.
RegisteredHandlers []string // file:line of all registered handlers. RegisteredHandlers []string // file:line of all registered handlers.
@@ -6436,7 +6436,7 @@ const (
// //
// Example at: // Example at:
// https://github.com/kataras/iris/tree/main/_examples/routing/writing-a-middleware/share-funcs // 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...) f := newFunc(name, fn, persistenceArgs...)
ctx.values.Set(funcsContextPrefixKey+name, f) 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 // For a more complete solution without limiations navigate through
// the Iris Dependency Injection feature instead. // 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) fn, ok := ctx.GetFunc(name)
if !ok || fn == nil { if !ok || fn == nil {
return nil, ErrNotFound 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. // This method uses the `SetFunc` method under the hoods.
// //
// See `Logout` method too. // 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...) ctx.SetFunc(funcLogoutContextKey, fn, persistenceArgs...)
} }
// Logout calls the registered logout function. // Logout calls the registered logout function.
// Returns ErrNotFound if a logout function was not specified // Returns ErrNotFound if a logout function was not specified
// by a prior call of `SetLogoutFunc`. // 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...) _, err := ctx.CallFunc(funcLogoutContextKey, args...)
return err return err
} }
@@ -6505,13 +6505,13 @@ const userContextKey = "iris.user"
// //
// The "i" input argument can be: // The "i" input argument can be:
// - A value which completes the User interface // - 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 whole User interface
// - A value which does not complete the User interface at all // - A value which does not complete the User interface at all
// (only its `User().GetRaw` method is available). // (only its `User().GetRaw` method is available).
// //
// Look the `User` method to retrieve it. // Look the `User` method to retrieve it.
func (ctx *Context) SetUser(i interface{}) error { func (ctx *Context) SetUser(i any) error {
if i == nil { if i == nil {
ctx.values.Remove(userContextKey) ctx.values.Remove(userContextKey)
return nil return nil
@@ -6615,8 +6615,8 @@ func (ctx *Context) Err() error {
// if no value is associated with key. Successive calls to Value with // if no value is associated with key. Successive calls to Value with
// the same key returns the same result. // the same key returns the same result.
// //
// Shortcut of Request().Context().Value(key interface{}) interface{}. // Shortcut of Request().Context().Value(key any) any.
func (ctx *Context) Value(key interface{}) interface{} { 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 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 { if entry, exists := ctx.values.GetEntry(keyStr); exists {
return entry.ValueRaw return entry.ValueRaw
@@ -6633,14 +6633,14 @@ const idContextKey = "iris.context.id"
// so it can be rendered on `Context.String` method. // so it can be rendered on `Context.String` method.
// //
// See `GetID` and `middleware/requestid` too. // See `GetID` and `middleware/requestid` too.
func (ctx *Context) SetID(id interface{}) { func (ctx *Context) SetID(id any) {
ctx.values.Set(idContextKey, id) ctx.values.Set(idContextKey, id)
} }
// GetID returns the Request Context's ID. // GetID returns the Request Context's ID.
// It returns nil if not given by a prior `SetID` call. // It returns nil if not given by a prior `SetID` call.
// See `middleware/requestid` too. // See `middleware/requestid` too.
func (ctx *Context) GetID() interface{} { func (ctx *Context) GetID() any {
return ctx.values.Get(idContextKey) return ctx.values.Get(idContextKey)
} }
+8 -8
View File
@@ -14,15 +14,15 @@ var ErrInvalidArgs = errors.New("invalid arguments")
// See its `buildMeta` and `call` internal methods. // See its `buildMeta` and `call` internal methods.
type Func struct { type Func struct {
RegisterName string // the name of which this function is registered, for information only. RegisterName string // the name of which this function is registered, for information only.
Raw interface{} // the Raw function, can be used for custom casting. Raw any // the Raw function, can be used for custom casting.
PersistenceArgs []interface{} // the persistence input arguments given on registration. PersistenceArgs []any // the persistence input arguments given on registration.
once sync.Once // guards build once, on first call. once sync.Once // guards build once, on first call.
// Available after the first call. // Available after the first call.
Meta *FuncMeta Meta *FuncMeta
} }
func newFunc(name string, fn interface{}, persistenceArgs ...interface{}) *Func { func newFunc(name string, fn any, persistenceArgs ...any) *Func {
return &Func{ return &Func{
RegisterName: name, RegisterName: name,
Raw: fn, Raw: fn,
@@ -37,8 +37,8 @@ type FuncMeta struct {
HandlerWithErr func(*Context) error // when it's just a handler which returns an error. HandlerWithErr func(*Context) error // when it's just a handler which returns an error.
RawFunc func() // when it's just a func. RawFunc func() // when it's just a func.
RawFuncWithErr func() error // when it's just a func which returns an error. RawFuncWithErr func() error // when it's just a func which returns an error.
RawFuncArgs func(...interface{}) RawFuncArgs func(...any)
RawFuncArgsWithErr func(...interface{}) error RawFuncArgsWithErr func(...any) error
Value reflect.Value Value reflect.Value
Type reflect.Type Type reflect.Type
@@ -65,10 +65,10 @@ func (f *Func) buildMeta() {
case func() error: case func() error:
f.Meta = &FuncMeta{RawFuncWithErr: fn} f.Meta = &FuncMeta{RawFuncWithErr: fn}
return return
case func(...interface{}): case func(...any):
f.Meta = &FuncMeta{RawFuncArgs: fn} f.Meta = &FuncMeta{RawFuncArgs: fn}
return return
case func(...interface{}) error: case func(...any) error:
f.Meta = &FuncMeta{RawFuncArgsWithErr: fn} f.Meta = &FuncMeta{RawFuncArgsWithErr: fn}
return return
} }
@@ -119,7 +119,7 @@ func (f *Func) buildMeta() {
f.Meta = &meta 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) f.once.Do(f.buildMeta)
meta := f.Meta meta := f.Meta
+15 -15
View File
@@ -34,7 +34,7 @@ var ErrNotSupported = errors.New("not supported")
// - UserPartial (a wrapper by SetUser) // - UserPartial (a wrapper by SetUser)
type User interface { type User interface {
// GetRaw should return the raw instance of the user, if supported. // GetRaw should return the raw instance of the user, if supported.
GetRaw() (interface{}, error) GetRaw() (any, error)
// GetAuthorization should return the authorization method, // GetAuthorization should return the authorization method,
// e.g. Basic Authentication. // e.g. Basic Authentication.
GetAuthorization() (string, error) GetAuthorization() (string, error)
@@ -60,12 +60,12 @@ type User interface {
// GetField should optionally return a dynamic field // GetField should optionally return a dynamic field
// based on its key. Useful for custom user fields. // based on its key. Useful for custom user fields.
// Keep in mind that these fields are encoded as a separate JSON key. // Keep in mind that these fields are encoded as a separate JSON key.
GetField(key string) (interface{}, error) GetField(key string) (any, error)
} /* Notes: } /* Notes:
We could use a structure of User wrapper and separate interfaces for each of the methods 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` so they return ErrNotSupported if the implementation is missing it, so the `Features`
field and HasUserFeature can be omitted and 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 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. 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. But we dont as it has many disadvantages, unless is requested.
@@ -95,7 +95,7 @@ type SimpleUser struct {
var _ User = (*SimpleUser)(nil) var _ User = (*SimpleUser)(nil)
// GetRaw returns itself. // GetRaw returns itself.
func (u *SimpleUser) GetRaw() (interface{}, error) { func (u *SimpleUser) GetRaw() (any, error) {
return u, nil return u, nil
} }
@@ -156,7 +156,7 @@ func (u *SimpleUser) GetToken() ([]byte, error) {
// GetField optionally returns a dynamic field from the `Fields` field // GetField optionally returns a dynamic field from the `Fields` field
// based on its key. // based on its key.
func (u *SimpleUser) GetField(key string) (interface{}, error) { func (u *SimpleUser) GetField(key string) (any, error) {
if u.Fields == nil { if u.Fields == nil {
return nil, ErrNotSupported return nil, ErrNotSupported
} }
@@ -164,10 +164,10 @@ func (u *SimpleUser) GetField(key string) (interface{}, error) {
return u.Fields[key], nil 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: // Usage:
// //
// user := map[string]interface{}{ // user := map[string]any{
// "username": "kataras", // "username": "kataras",
// "age" : 27, // "age" : 27,
// } // }
@@ -189,7 +189,7 @@ type UserMap Map
var _ User = UserMap{} var _ User = UserMap{}
// GetRaw returns the underline map. // GetRaw returns the underline map.
func (u UserMap) GetRaw() (interface{}, error) { func (u UserMap) GetRaw() (any, error) {
return Map(u), nil 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". // 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. // 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 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. isTitle := unicode.IsTitle(rune(key[0])) // if starts with uppercase.
if isTitle { if isTitle {
key = strings.ToLower(key) key = strings.ToLower(key)
@@ -333,7 +333,7 @@ type (
} }
userGetField interface { userGetField interface {
GetField(string) interface{} GetField(string) any
} }
// UserPartial is a User. // UserPartial is a User.
@@ -341,7 +341,7 @@ type (
// may or may not complete the whole User interface. // may or may not complete the whole User interface.
// See Context.SetUser. // See Context.SetUser.
UserPartial struct { UserPartial struct {
Raw interface{} `json:"raw"` Raw any `json:"raw"`
userGetAuthorization `json:",omitempty"` userGetAuthorization `json:",omitempty"`
userGetAuthorizedAt `json:",omitempty"` userGetAuthorizedAt `json:",omitempty"`
userGetID `json:",omitempty"` userGetID `json:",omitempty"`
@@ -356,7 +356,7 @@ type (
var _ User = (*UserPartial)(nil) var _ User = (*UserPartial)(nil)
func newUserPartial(i interface{}) *UserPartial { func newUserPartial(i any) *UserPartial {
if i == nil { if i == nil {
return nil return nil
} }
@@ -407,7 +407,7 @@ func newUserPartial(i interface{}) *UserPartial {
} }
// GetRaw returns the original raw instance of the user. // GetRaw returns the original raw instance of the user.
func (u *UserPartial) GetRaw() (interface{}, error) { func (u *UserPartial) GetRaw() (any, error) {
if u == nil { if u == nil {
return nil, ErrNotSupported return nil, ErrNotSupported
} }
@@ -496,7 +496,7 @@ func (u *UserPartial) GetToken() ([]byte, error) {
// GetField should optionally return a dynamic field // GetField should optionally return a dynamic field
// based on its key. Useful for custom user fields. // based on its key. Useful for custom user fields.
// Keep in mind that these fields are encoded as a separate JSON key. // 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 { if v := u.userGetField; v != nil {
return v.GetField(key), nil return v.GetField(key), nil
} }
+2 -2
View File
@@ -17,7 +17,7 @@ import (
// It affects the view engine's filesystem resolver. // It affects the view engine's filesystem resolver.
// //
// This package-level variable can be modified on initialization. // 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 { if fsOrDir == nil {
return noOpFS{} 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. // It affects the Application's API Builder's `HandleDir` method.
// //
// This package-level variable can be modified on initialization. // 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 var fileSystem http.FileSystem
switch v := fsOrDir.(type) { switch v := fsOrDir.(type) {
case string: case string:
+8 -8
View File
@@ -131,7 +131,7 @@ type Handler = func(*Context)
// See `Handler` for more. // See `Handler` for more.
type Handlers = []Handler type Handlers = []Handler
func valueOf(v interface{}) reflect.Value { func valueOf(v any) reflect.Value {
if val, ok := v.(reflect.Value); ok { if val, ok := v.(reflect.Value); ok {
return val return val
} }
@@ -142,7 +142,7 @@ func valueOf(v interface{}) reflect.Value {
// HandlerName returns the handler's function name. // HandlerName returns the handler's function name.
// See `Context.HandlerName` method to get function name of the current running handler in the chain. // See `Context.HandlerName` method to get function name of the current running handler in the chain.
// See `SetHandlerName` too. // See `SetHandlerName` too.
func HandlerName(h interface{}) string { func HandlerName(h any) string {
pc := valueOf(h).Pointer() pc := valueOf(h).Pointer()
fn := runtime.FuncForPC(pc) fn := runtime.FuncForPC(pc)
name := fn.Name() name := fn.Name()
@@ -166,10 +166,10 @@ func HandlerName(h interface{}) string {
// or to determinate if end-developer // or to determinate if end-developer
// called the same exactly Use/UseRouter/Done... API methods // called the same exactly Use/UseRouter/Done... API methods
// so framework can give a warning. // so framework can give a warning.
func HandlersNames(handlers ...interface{}) string { func HandlersNames(handlers ...any) string {
if len(handlers) == 1 { if len(handlers) == 1 {
if hs, ok := handlers[0].(Handlers); ok { if hs, ok := handlers[0].(Handlers); ok {
asInterfaces := make([]interface{}, 0, len(hs)) asInterfaces := make([]any, 0, len(hs))
for _, h := range hs { for _, h := range hs {
asInterfaces = append(asInterfaces, h) asInterfaces = append(asInterfaces, h)
} }
@@ -188,14 +188,14 @@ func HandlersNames(handlers ...interface{}) string {
// HandlerFileLine returns the handler's file and line information. // 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. // 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() pc := valueOf(h).Pointer()
return runtime.FuncForPC(pc).FileLine(pc) return runtime.FuncForPC(pc).FileLine(pc)
} }
// HandlerFileLineRel same as `HandlerFileLine` but it returns the path // HandlerFileLineRel same as `HandlerFileLine` but it returns the path
// corresponding to its relative based on the package-level "WorkingDir" variable. // 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) file, line = HandlerFileLine(h)
if relFile, err := filepath.Rel(WorkingDir, file); err == nil { if relFile, err := filepath.Rel(WorkingDir, file); err == nil {
if !strings.HasPrefix(relFile, "..") { 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 // MainHandlerName tries to find the main handler that end-developer
// registered on the provided chain of handlers and returns its function name. // 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 { if len(handlers) == 0 {
return return
} }
if hs, ok := handlers[0].(Handlers); ok { if hs, ok := handlers[0].(Handlers); ok {
tmp := make([]interface{}, 0, len(hs)) tmp := make([]any, 0, len(hs))
for _, h := range hs { for _, h := range hs {
tmp = append(tmp, h) tmp = append(tmp, h)
} }
+3 -3
View File
@@ -7,8 +7,8 @@ import "golang.org/x/text/language"
type I18nReadOnly interface { type I18nReadOnly interface {
Tags() []language.Tag Tags() []language.Tag
GetLocale(ctx *Context) Locale GetLocale(ctx *Context) Locale
Tr(lang string, key string, args ...interface{}) string Tr(lang string, key string, args ...any) string
TrContext(ctx *Context, key string, args ...interface{}) string TrContext(ctx *Context, key string, args ...any) string
} }
// Locale is the interface which returns from a `Localizer.GetLocale` method. // 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. // Same as `Tag().String()` but it's static.
Language() string Language() string
// GetMessage should return translated text based on the given "key". // GetMessage should return translated text based on the given "key".
GetMessage(key string, args ...interface{}) string GetMessage(key string, args ...any) string
} }
+1 -1
View File
@@ -11,7 +11,7 @@ type Pool struct {
} }
// New creates and returns a new context pool. // 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}} return &Pool{pool: &sync.Pool{New: newFunc}}
} }
+7 -7
View File
@@ -15,7 +15,7 @@ import (
// write an "application/problem+json" response. // write an "application/problem+json" response.
// //
// Read more at: https://github.com/kataras/iris/blob/main/_examples/routing/http-errors. // 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. // NewProblem retruns a new Problem.
// Head over to the `Problem` type godoc for more. // 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 // TempKey sets a temporary key-value pair, which is being removed
// on the its first get. // 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) return p.Key(problemTempKeyPrefix+key, value)
} }
// GetTempKey returns the temp value based on "key" and removes it. // 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 key = problemTempKeyPrefix + key
v, ok := p[key] v, ok := p[key]
if ok { if ok {
@@ -116,7 +116,7 @@ func (p Problem) GetTempKey(key string) interface{} {
} }
// Key sets a custom key-value pair. // 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 p[key] = value
return p return p
} }
@@ -277,20 +277,20 @@ type ProblemOptions struct {
// 300 * time.Second, // 300 * time.Second,
// "5m", // "5m",
// 300 // 300
RetryAfter interface{} RetryAfter any
// A function that, if specified, can dynamically set // A function that, if specified, can dynamically set
// retry-after based on the request. Useful for ProblemOptions reusability. // retry-after based on the request. Useful for ProblemOptions reusability.
// Should return time.Time, time.Duration, int64, int, float64 or string. // Should return time.Time, time.Duration, int64, int, float64 or string.
// //
// Overrides the RetryAfter field. // Overrides the RetryAfter field.
RetryAfterFunc func(*Context) interface{} RetryAfterFunc func(*Context) any
} }
func parseDurationToSeconds(dur time.Duration) int64 { func parseDurationToSeconds(dur time.Duration) int64 {
return int64(math.Round(dur.Seconds())) 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 // https://tools.ietf.org/html/rfc7231#section-7.1.3
// Retry-After = HTTP-date / delay-seconds // Retry-After = HTTP-date / delay-seconds
switch v := value.(type) { switch v := value.(type) {
+18 -18
View File
@@ -70,7 +70,7 @@ func (r *RequestParams) GetEntry(key string) memstore.Entry {
// Visit accepts a visitor which will be filled // Visit accepts a visitor which will be filled
// by the key-value params. // by the key-value params.
func (r *RequestParams) Visit(visitor func(key string, value string)) { 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. 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 // The value is a function which accepts the parameter index
// and it should return the value as the parameter type evaluator expects it. // 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) <T> { // return func(ctx *Context) <T> {
// return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(<T>) // return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(<T>)
// } // }
@@ -238,8 +238,8 @@ func (r *RequestParams) GetIntUnslashed(key string) (int, bool) {
// and parameter index based on the hero/mvc function added // and parameter index based on the hero/mvc function added
// in order to support the MVC.HandleMany("GET", "/path/{ps}/{pssecond} /path/{ps}") // in order to support the MVC.HandleMany("GET", "/path/{ps}/{pssecond} /path/{ps}")
// when on the second requested path, the 'pssecond' should be empty. // when on the second requested path, the 'pssecond' should be empty.
var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ var ParamResolvers = map[reflect.Type]func(paramIndex int) any{
reflect.TypeOf(""): func(paramIndex int) interface{} { reflect.TypeOf(""): func(paramIndex int) any {
return func(ctx *Context) string { return func(ctx *Context) string {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return "" return ""
@@ -247,7 +247,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(string) 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 { return func(ctx *Context) int {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -257,7 +257,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int) 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 { return func(ctx *Context) int8 {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -265,7 +265,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int8) 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 { return func(ctx *Context) int16 {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -273,7 +273,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int16) 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 { return func(ctx *Context) int32 {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -281,7 +281,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int32) 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 { return func(ctx *Context) int64 {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -289,7 +289,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int64) 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 { return func(ctx *Context) uint {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -297,7 +297,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint) 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 { return func(ctx *Context) uint8 {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -305,7 +305,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint8) 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 { return func(ctx *Context) uint16 {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -313,7 +313,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint16) 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 { return func(ctx *Context) uint32 {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -321,7 +321,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint32) 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 { return func(ctx *Context) uint64 {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return 0 return 0
@@ -329,7 +329,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint64) 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 { return func(ctx *Context) bool {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return false return false
@@ -337,7 +337,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(bool) 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 { return func(ctx *Context) time.Time {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return unixEpochTime return unixEpochTime
@@ -351,7 +351,7 @@ var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
return v 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 { return func(ctx *Context) time.Weekday {
if ctx.Params().Len() <= paramIndex { if ctx.Params().Len() <= paramIndex {
return time.Sunday return time.Sunday
@@ -382,7 +382,7 @@ func ParamResolverByTypeAndIndex(typ reflect.Type, paramIndex int) (reflect.Valu
/* NO: /* NO:
// This could work but its result is not exact type, so direct binding is not possible. // This could work but its result is not exact type, so direct binding is not possible.
resolver := m.ParamResolver resolver := m.ParamResolver
fn := func(ctx *context.Context) interface{} { fn := func(ctx *context.Context) any {
entry, _ := ctx.Params().GetEntry(paramName) entry, _ := ctx.Params().GetEntry(paramName)
return resolver(entry) return resolver(entry)
} }
+1 -1
View File
@@ -17,7 +17,7 @@ var Recorder = func(ctx *Context) {
ctx.Next() 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. // AcquireResponseRecorder returns a new *AcquireResponseRecorder from the pool.
// Releasing is done automatically when request and response is done. // Releasing is done automatically when request and response is done.
+1 -1
View File
@@ -127,7 +127,7 @@ type ResponseWriterWriteTo interface {
// | Response Writer Implementation | // | 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. // AcquireResponseWriter returns a new *ResponseWriter from the pool.
// Releasing is done automatically when request and response is done. // Releasing is done automatically when request and response is done.
+1 -1
View File
@@ -64,7 +64,7 @@ type RouteReadOnly interface {
// Property returns a specific property based on its "key" // Property returns a specific property based on its "key"
// of this route's Party owner. // of this route's Party owner.
Property(key string) (interface{}, bool) Property(key string) (any, bool)
// Sitemap properties: https://www.sitemaps.org/protocol.html // Sitemap properties: https://www.sitemaps.org/protocol.html
+3 -3
View File
@@ -10,7 +10,7 @@ import (
type ErrViewNotExist struct { type ErrViewNotExist struct {
Name string Name string
IsLayout bool IsLayout bool
Data interface{} Data any
} }
// Error completes the `error` interface. // Error completes the `error` interface.
@@ -29,7 +29,7 @@ type ViewEngine interface {
// Load should load the templates from the given FileSystem. // Load should load the templates from the given FileSystem.
Load() error Load() error
// ExecuteWriter should execute a template by its filename with an optional layout and bindingData. // 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) // Ext should return the final file extension (including the dot)
// which this view engine is responsible to render. // which this view engine is responsible to render.
// If the filename extension on ExecuteWriter is empty then this is appended. // If the filename extension on ExecuteWriter is empty then this is appended.
@@ -42,5 +42,5 @@ type ViewEngine interface {
// like {{ url }}, {{ urlpath }} and {{ tr }}. // like {{ url }}, {{ urlpath }} and {{ tr }}.
type ViewEngineFuncer interface { type ViewEngineFuncer interface {
// AddFunc should adds a function to the template's function map. // AddFunc should adds a function to the template's function map.
AddFunc(funcName string, funcBody interface{}) AddFunc(funcName string, funcBody any)
} }
+12 -12
View File
@@ -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 *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. // 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". // 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 { if err == nil {
return nil return nil
} }
@@ -66,7 +66,7 @@ func Errors(err error, conv bool) []error {
return []error{err} return []error{err}
} }
func Type(err error) interface{} { func Type(err error) any {
if err == nil { if err == nil {
return nil return nil
} }
@@ -96,7 +96,7 @@ func Fill(parent *Group, errors []*Error) {
// Group that it's created through Group's `Err` and `Errf` methods. // Group that it's created through Group's `Err` and `Errf` methods.
type Error struct { type Error struct {
Err error `json:"error" xml:"Error" yaml:"Error" toml:"Error" sql:"error"` Err error `json:"error" xml:"Error" yaml:"Error" toml:"Error" sql:"error"`
Type interface{} `json:"type" xml:"Type" yaml:"Type" toml:"Type" sql:"type"` Type any `json:"type" xml:"Type" yaml:"Type" toml:"Type" sql:"type"`
} }
// Error returns the error message of the "Err". // 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: ?}. // 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 { if target == nil {
return target == e return target == e
} }
@@ -157,10 +157,10 @@ func (e *Error) As(target interface{}) bool {
type Group struct { type Group struct {
parent *Group parent *Group
// a list of children groups, used to get or create new group through Group method. // 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 depth int
Type interface{} Type any
Errors []error // []*Error 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. // 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. // New returns a new empty Group.
func New(typ interface{}) *Group { func New(typ any) *Group {
return &Group{ return &Group{
Type: typ, Type: typ,
IncludeChildren: true, 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. // 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 { if g.children == nil {
g.children = make(map[interface{}]*Group) g.children = make(map[any]*Group)
} else { } else {
for _, child := range g.children { for _, child := range g.children {
if child.Type == typ { 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. // 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...) err := fmt.Errorf(format, args...)
g.Add(err) g.Add(err)
return err return err
@@ -298,7 +298,7 @@ func (g *Group) Err(err error) error {
if !ok { if !ok {
if ge, ok := err.(*Group); ok { if ge, ok := err.(*Group); ok {
if g.children == nil { if g.children == nil {
g.children = make(map[interface{}]*Group) g.children = make(map[any]*Group)
} }
g.children[ge.Type] = ge 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. // 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...)) return g.Err(fmt.Errorf(format, args...))
} }
+1 -1
View File
@@ -145,7 +145,7 @@ func TestGroup(t *testing.T) {
t.Run("Walk", func(t *testing.T) { t.Run("Walk", func(t *testing.T) {
expectedEntries := 4 expectedEntries := 4
_ = Walk(g, func(typ interface{}, err error) { _ = Walk(g, func(typ any, err error) {
g.IncludeChildren = false g.IncludeChildren = false
childAPIErrorsGroup.IncludeChildren = false childAPIErrorsGroup.IncludeChildren = false
childAPIErrorsGroup2.IncludeChildren = false childAPIErrorsGroup2.IncludeChildren = false
+1 -1
View File
@@ -14,7 +14,7 @@ import (
// .FromStd(h http.Handler) // .FromStd(h http.Handler)
// .FromStd(func(w http.ResponseWriter, r *http.Request)) // .FromStd(func(w http.ResponseWriter, r *http.Request))
// .FromStd(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) // .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) { switch h := handler.(type) {
case context.Handler: case context.Handler:
return h return h
+12 -12
View File
@@ -18,12 +18,12 @@ type (
// ValueSetter is the interface which can be accepted as a generic solution of RequestParams or memstore when Set is the only requirement, // 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. // i.e internally on macro/template/TemplateParam#Eval:paramChanger.
ValueSetter interface { 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 is the entry of the context storage Store - .Values()
Entry struct { Entry struct {
Key string `json:"key" msgpack:"key" yaml:"Key" toml:"Value"` Key string `json:"key" msgpack:"key" yaml:"Key" toml:"Value"`
ValueRaw interface{} `json:"value" msgpack:"value" yaml:"Value" toml:"Value"` ValueRaw any `json:"value" msgpack:"value" yaml:"Value" toml:"Value"`
immutable bool // if true then it can't change by its caller. immutable bool // if true then it can't change by its caller.
} }
@@ -47,7 +47,7 @@ var _ ValueSetter = (*Store)(nil)
// //
// If the "k" kind is not a string or int or int64 or bool // 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. // 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 { switch k {
case reflect.String: case reflect.String:
v := e.StringDefault("__$nf") 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. // Do NOT use this method directly, prefer` errors.As` method as explained above.
// //
// Implements: go/src/errors/wrap.go#84 // 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) v, ok := target.(*ErrEntryNotFound)
if !ok { if !ok {
return false return false
@@ -721,7 +721,7 @@ func (e Entry) WeekdayDefault(def time.Weekday) (time.Weekday, error) {
// Value returns the value of the entry, // Value returns the value of the entry,
// respects the immutable. // respects the immutable.
func (e Entry) Value() interface{} { func (e Entry) Value() any {
if e.immutable { if e.immutable {
// take its value, no pointer even if set with a reference. // take its value, no pointer even if set with a reference.
vv := reflect.Indirect(reflect.ValueOf(e.ValueRaw)) 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 // 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. // 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 args := *r
n := len(args) 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. // it will return the entry and a false boolean if the entry exists and it has been updated.
// //
// See `SetImmutable` and `Get`. // 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) 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`. // Use it consistently, it's far slower than `Set`.
// Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081 // 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) 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. // GetDefault returns the entry's value based on its key.
// If not found returns "def". // If not found returns "def".
// This function checks for immutability as well, the rest don't. // 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) v, ok := r.GetEntry(key)
if !ok || v.ValueRaw == nil { if !ok || v.ValueRaw == nil {
return def return def
@@ -874,14 +874,14 @@ func (r *Store) Exists(key string) bool {
// Get returns the entry's value based on its key. // Get returns the entry's value based on its key.
// If not found returns nil. // If not found returns nil.
func (r *Store) Get(key string) interface{} { func (r *Store) Get(key string) any {
return r.GetDefault(key, nil) return r.GetDefault(key, nil)
} }
// GetOrSet is like `GetDefault` but it accepts a function which is // GetOrSet is like `GetDefault` but it accepts a function which is
// fired and its result is used to `Set` if // fired and its result is used to `Set` if
// the "key" was not found or its value is nil. // 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 { if v, ok := r.GetEntry(key); ok && v.ValueRaw != nil {
return v.Value() 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 // Visit accepts a visitor which will be filled
// by the key-value objects. // 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 args := *r
for i, n := 0, len(args); i < n; i++ { for i, n := 0, len(args); i < n; i++ {
kv := args[i] kv := args[i]
+1 -1
View File
@@ -150,7 +150,7 @@ func TestJSON(t *testing.T) {
expected, got := p.Get(v.Key), v.ValueRaw expected, got := p.Get(v.Key), v.ValueRaw
if ex, g := fmt.Sprintf("%v", expected), fmt.Sprintf("%v", got); ex != g { 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). // was struct but converted into map (as expected).
b1, _ := json.Marshal(expected) b1, _ := json.Marshal(expected)
b2, _ := json.Marshal(got) b2, _ := json.Marshal(got)
+5 -5
View File
@@ -360,7 +360,7 @@ func (api *APIBuilder) EnsureStaticBindings() Party {
// RegisterDependency calls the `ConfigureContainer.RegisterDependency` method // RegisterDependency calls the `ConfigureContainer.RegisterDependency` method
// with the provided value(s). See `HandleFunc` and `PartyConfigure` methods too. // 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() diContainer := api.ConfigureContainer()
for i, dependency := range dependencies { for i, dependency := range dependencies {
if dependency == nil { if dependency == nil {
@@ -442,7 +442,7 @@ func (api *APIBuilder) RegisterDependency(dependencies ...interface{}) {
// the dependency injection, mvc and function handlers. // the dependency injection, mvc and function handlers.
// //
// This method is just a shortcut of the `ConfigureContainer().Handle`. // 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...) return api.ConfigureContainer().Handle(method, relativePath, handlersFn...)
} }
@@ -451,7 +451,7 @@ func (api *APIBuilder) HandleFunc(method, relativePath string, handlersFn ...int
// or a result of <T> and/or an error. // or a result of <T> and/or an error.
// //
// This method is just a shortcut of the `ConfigureContainer().Use`. // 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...) api.ConfigureContainer().Use(handlersFn...)
} }
@@ -636,7 +636,7 @@ func (api *APIBuilder) HandleMany(methodOrMulti string, relativePathorMulti stri
// //
// Examples: // Examples:
// https://github.com/kataras/iris/tree/main/_examples/file-server // 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 options := DefaultDirOptions
if len(opts) > 0 { if len(opts) > 0 {
options = opts[0] options = opts[0]
@@ -1401,7 +1401,7 @@ func (api *APIBuilder) MiddlewareExists(handlerNameOrFunc any) bool {
// Returns the Party itself for chain calls. // Returns the Party itself for chain calls.
// //
// Should be called before children routes regitration. // Should be called before children routes regitration.
func (api *APIBuilder) RemoveHandler(namesOrHandlers ...interface{}) Party { func (api *APIBuilder) RemoveHandler(namesOrHandlers ...any) Party {
var counter *int var counter *int
for _, nameOrHandler := range namesOrHandlers { for _, nameOrHandler := range namesOrHandlers {
+20 -20
View File
@@ -20,7 +20,7 @@ type APIContainer struct {
// Party returns a child of this `APIContainer` featured with Dependency Injection. // Party returns a child of this `APIContainer` featured with Dependency Injection.
// Like the `Self.Party` method does for the common Router Groups. // 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...) handlers := api.convertHandlerFuncs(relativePath, handlersFn...)
p := api.Self.Party(relativePath, handlers...) p := api.Self.Party(relativePath, handlers...)
return p.ConfigureContainer() return p.ConfigureContainer()
@@ -67,7 +67,7 @@ func (api *APIContainer) OnError(errorHandler func(*context.Context, error)) {
// - RegisterDependency(func(User) OtherResponse {...}) // - RegisterDependency(func(User) OtherResponse {...})
// //
// See `OnError`, `Use`, `Done` and `Handle` too. // 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) 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. // 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 fullpath := api.Self.GetRelPath() + relativePath
paramsCount := macro.CountParams(fullpath, *api.Self.Macros()) paramsCount := macro.CountParams(fullpath, *api.Self.Macros())
@@ -136,7 +136,7 @@ func (api *APIContainer) convertHandlerFuncs(relativePath string, handlersFn ...
return handlers 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. // Fix main handler name and source modified by execution rules wrapper.
route.MainHandlerName, route.MainHandlerIndex = context.MainHandlerName(handlersFn...) route.MainHandlerName, route.MainHandlerIndex = context.MainHandlerName(handlersFn...)
if len(handlersFn) > route.MainHandlerIndex { 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 // Handler receives a function which can receive dependencies and output result
// and returns a common Iris Handler, useful for Versioning API integration otherwise // and returns a common Iris Handler, useful for Versioning API integration otherwise
// the `Handle/Get/Post...` methods are preferable. // 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 paramsCount := macro.CountParams(api.Self.GetRelPath(), *api.Self.Macros()) + handlerParamsCount
return api.Container.HandlerWithParams(handlerFn, paramsCount) 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. // Use same as `Self.Use` but it accepts dynamic functions as its "handlersFn" input.
// //
// See `OnError`, `RegisterDependency`, `Done` and `Handle` for more. // See `OnError`, `RegisterDependency`, `Done` and `Handle` for more.
func (api *APIContainer) Use(handlersFn ...interface{}) { func (api *APIContainer) Use(handlersFn ...any) {
handlers := api.convertHandlerFuncs("/", handlersFn...) handlers := api.convertHandlerFuncs("/", handlersFn...)
api.Self.Use(handlers...) api.Self.Use(handlers...)
} }
// Done same as `Self.Done` but it accepts dynamic functions as its "handlersFn" input. // Done same as `Self.Done` but it accepts dynamic functions as its "handlersFn" input.
// See `OnError`, `RegisterDependency`, `Use` and `Handle` for more. // See `OnError`, `RegisterDependency`, `Use` and `Handle` for more.
func (api *APIContainer) Done(handlersFn ...interface{}) { func (api *APIContainer) Done(handlersFn ...any) {
handlers := api.convertHandlerFuncs("/", handlersFn...) handlers := api.convertHandlerFuncs("/", handlersFn...)
api.Self.Done(handlers...) 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`. // the end-developer should output an error and return `iris.ErrStopExecution`.
// //
// See `OnError`, `RegisterDependency`, `Use`, `Done`, `Get`, `Post`, `Put`, `Patch` and `Delete` too. // 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...) handlers := api.convertHandlerFuncs(relativePath, handlersFn...)
route := api.Self.Handle(method, relativePath, handlers...) route := api.Self.Handle(method, relativePath, handlers...)
fixRouteInfo(route, handlersFn) 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. // 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. // 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...) return api.Handle(http.MethodGet, relativePath, handlersFn...)
} }
// Post registers a route for the Post HTTP Method. // 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. // 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...) return api.Handle(http.MethodPost, relativePath, handlersFn...)
} }
// Put registers a route for the Put HTTP Method. // 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. // 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...) return api.Handle(http.MethodPut, relativePath, handlersFn...)
} }
// Delete registers a route for the Delete HTTP Method. // 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. // 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...) return api.Handle(http.MethodDelete, relativePath, handlersFn...)
} }
// Connect registers a route for the Connect HTTP Method. // 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. // 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...) return api.Handle(http.MethodConnect, relativePath, handlersFn...)
} }
// Head registers a route for the Head HTTP Method. // 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. // 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...) return api.Handle(http.MethodHead, relativePath, handlersFn...)
} }
// Options registers a route for the Options HTTP Method. // 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. // 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...) return api.Handle(http.MethodOptions, relativePath, handlersFn...)
} }
// Patch registers a route for the Patch HTTP Method. // 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. // 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...) return api.Handle(http.MethodPatch, relativePath, handlersFn...)
} }
// Trace registers a route for the Trace HTTP Method. // 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. // 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...) return api.Handle(http.MethodTrace, relativePath, handlersFn...)
} }
@@ -258,7 +258,7 @@ func (api *APIContainer) Trace(relativePath string, handlersFn ...interface{}) *
// Options // Options
// Connect // Connect
// Trace // 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...) handlers := api.convertHandlerFuncs(relativePath, handlersFn...)
for _, m := range AllMethods { 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. // 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 // Read more at: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
// Look `OnAnyErrorCode` too. // 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...) handlers := api.convertHandlerFuncs("/{tail:path}", handlersFn...)
return api.Self.OnErrorCode(statusCode, handlers...) 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 // OnAnyErrorCode registers a handlers chain for all error codes
// (4xxx and 5xxx, change the `ClientErrorCodes` and `ServerErrorCodes` variables to modify those) // (4xxx and 5xxx, change the `ClientErrorCodes` and `ServerErrorCodes` variables to modify those)
// Look `OnErrorCode` too. // Look `OnErrorCode` too.
func (api *APIContainer) OnAnyErrorCode(handlersFn ...interface{}) []*Route { func (api *APIContainer) OnAnyErrorCode(handlersFn ...any) []*Route {
handlers := api.convertHandlerFuncs("/{tail:path}", handlersFn...) handlers := api.convertHandlerFuncs("/{tail:path}", handlersFn...)
return api.Self.OnAnyErrorCode(handlers...) return api.Self.OnAnyErrorCode(handlers...)
} }
+1 -1
View File
@@ -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) ModTime() time.Time { return fi.modTime }
func (fi *fileInfo) IsDir() bool { return fi.isDir } func (fi *fileInfo) IsDir() bool { return fi.isDir }
func (fi *fileInfo) Size() int64 { return 0 } func (fi *fileInfo) Size() int64 { return 0 }
func (fi *fileInfo) Sys() interface{} { return fi } func (fi *fileInfo) Sys() any { return fi }
type dir struct { type dir struct {
os.FileInfo // *fileInfo os.FileInfo // *fileInfo
+5 -5
View File
@@ -33,7 +33,7 @@ type Party interface {
EnsureStaticBindings() Party EnsureStaticBindings() Party
// RegisterDependency calls the `ConfigureContainer.RegisterDependency` method // RegisterDependency calls the `ConfigureContainer.RegisterDependency` method
// with the provided value(s). See `HandleFunc` and `PartyConfigure` methods too. // 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. // 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 // 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 // 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. // the dependency injection, mvc and function handlers.
// //
// This method is just a shortcut for the `ConfigureContainer().Handle` one. // 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 // UseFunc registers a function which can accept one or more
// dependencies (see RegisterDependency) and returns an iris.Handler // dependencies (see RegisterDependency) and returns an iris.Handler
// or a result of <T> and/or an error. // or a result of <T> and/or an error.
// //
// This method is just a shortcut of the `ConfigureContainer().Use`. // This method is just a shortcut of the `ConfigureContainer().Use`.
UseFunc(handlersFn ...interface{}) UseFunc(handlersFn ...any)
// GetRelPath returns the current party's relative path. // GetRelPath returns the current party's relative path.
// i.e: // i.e:
@@ -245,7 +245,7 @@ type Party interface {
// Returns the Party itself for chain calls. // Returns the Party itself for chain calls.
// //
// Should be called before children routes regitration. // 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`, // Reset removes all the begin and done handlers that may derived from the parent party via `Use` & `Done`,
// and the execution rules. // and the execution rules.
// Note that the `Reset` will not reset the handlers that are registered via `UseGlobal` & `DoneGlobal`. // Note that the `Reset` will not reset the handlers that are registered via `UseGlobal` & `DoneGlobal`.
@@ -338,7 +338,7 @@ type Party interface {
// //
// Examples: // Examples:
// https://github.com/kataras/iris/tree/main/_examples/file-server // 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 // None registers an "offline" route
// see context.ExecRoute(routeName) and // see context.ExecRoute(routeName) and
+3 -3
View File
@@ -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. // 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) r := ps.provider.GetRoute(routeName)
if r == nil { if r == nil {
return "" return ""
@@ -348,7 +348,7 @@ func (ps *RoutePathReverser) Path(routeName string, paramValues ...interface{})
return r.ResolvePath(toStringSlice(paramValues)...) return r.ResolvePath(toStringSlice(paramValues)...)
} }
func toStringSlice(args []interface{}) (argsString []string) { func toStringSlice(args []any) (argsString []string) {
argsSize := len(args) argsSize := len(args)
if argsSize <= 0 { if argsSize <= 0 {
return 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). // 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 // 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 == "" { if ps.vhost == "" || ps.vscheme == "" {
return "not supported" return "not supported"
} }
+2 -2
View File
@@ -154,7 +154,7 @@ func (r *Route) UseOnce(handlers ...context.Handler) {
// Returns the total amount of handlers removed. // Returns the total amount of handlers removed.
// //
// Should be called before Application Build. // 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 { for _, nameOrHandler := range namesOrHandlers {
handlerName := "" handlerName := ""
switch h := nameOrHandler.(type) { switch h := nameOrHandler.(type) {
@@ -644,7 +644,7 @@ func (rd routeReadOnlyWrapper) MainHandlerIndex() int {
return rd.Route.MainHandlerIndex 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() properties := rd.Route.Party.Properties()
if properties != nil { if properties != nil {
if property, ok := properties[key]; ok { if property, ok := properties[key]; ok {
+3 -3
View File
@@ -101,16 +101,16 @@ func TestContainerInject(t *testing.T) {
func TestContainerUseResultHandler(t *testing.T) { func TestContainerUseResultHandler(t *testing.T) {
c := New() c := New()
resultLogger := func(next ResultHandler) ResultHandler { 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) t.Logf("%#+v", v)
return next(ctx, v) return next(ctx, v)
} }
} }
c.UseResultHandler(resultLogger) c.UseResultHandler(resultLogger)
expectedResponse := map[string]interface{}{"injected": true} expectedResponse := map[string]any{"injected": true}
c.UseResultHandler(func(next ResultHandler) ResultHandler { 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) return next(ctx, expectedResponse)
} }
}) })
+3 -3
View File
@@ -24,7 +24,7 @@ type (
// Contains its source location, the dependency handler (provider) itself and information // 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). // 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 { Dependency struct {
OriginalValue interface{} // Used for debugging and for logging only. OriginalValue any // Used for debugging and for logging only.
Source Source Source Source
Handle DependencyHandler Handle DependencyHandler
// It's the exact type of return to bind, if declared to return <T>, otherwise nil. // It's the exact type of return to bind, if declared to return <T>, 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. // NewDependency converts a function or a function which accepts other dependencies or static struct value to a *Dependency.
// //
// See `Container.Handler` for more. // 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...) return newDependency(dependency, false, false, nil, funcDependencies...)
} }
func newDependency( func newDependency(
dependency interface{}, dependency any,
disablePayloadAutoBinding bool, disablePayloadAutoBinding bool,
enableStructDependents bool, enableStructDependents bool,
matchDependency DependencyMatcher, matchDependency DependencyMatcher,
+4 -4
View File
@@ -11,8 +11,8 @@ import (
) )
type testDependencyTest struct { type testDependencyTest struct {
Dependency interface{} Dependency any
Expected interface{} Expected any
} }
func TestDependency(t *testing.T) { 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" return "1"
}, },
Expected: "1", Expected: "1",
}, },
{ {
Dependency: func(*context.Context) interface{} { Dependency: func(*context.Context) any {
return false return false
}, },
Expected: false, Expected: false,
+8 -8
View File
@@ -11,9 +11,9 @@ import (
) )
// ResultHandler describes the function type which should serve the "v" struct value. // 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 p, ok := v.(PreflightResult); ok {
if err := p.Preflight(ctx); err != nil { if err := p.Preflight(ctx); err != nil {
return err return err
@@ -183,7 +183,7 @@ func dispatchFuncResult(ctx *context.Context, values []reflect.Value, handler Re
// if not nil then check // if not nil then check
// for content type (or json default) and send the custom data object // for content type (or json default) and send the custom data object
// except when found == false or err != nil. // except when found == false or err != nil.
custom interface{} custom any
// if false then skip everything and fire 404. // if false then skip everything and fire 404.
found = true // defaults to true of course, otherwise will break :) 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 // dispatchCommon is being used internally to send
// commonly used data to the response writer with a smart way. // commonly used data to the response writer with a smart way.
func dispatchCommon(ctx *context.Context, 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 // if we have a false boolean as a return value
// then skip everything and fire a not found, // then skip everything and fire a not found,
// we even don't care about the given status code or the object or the content. // 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 // previously set "ContentType". If "Lang" and "Text" are not empty
// then this "Object" field becomes the template data that the // then this "Object" field becomes the template data that the
// locale text should use to be rendered. // locale text should use to be rendered.
Object interface{} Object any
// If Path is not empty then it will redirect // If Path is not empty then it will redirect
// the client to this Path, if Code is >= 300 and < 400 // 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 { type View struct {
Name string Name string
Layout string Layout string
Data interface{} // map or a custom struct. Data any // map or a custom struct.
Code int Code int
Err error Err error
} }
@@ -502,7 +502,7 @@ func (r View) Dispatch(ctx *context.Context) { // r as Response view.
} else { } else {
// else check if r.Data is map or struct, if struct convert it to map, // 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. // 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 { if m, ok := r.Data.(context.Map); ok {
setViewData(ctx, m) setViewData(ctx, m)
} else if reflect.Indirect(reflect.ValueOf(r.Data)).Kind() == reflect.Struct { } 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 { for k, v := range data {
ctx.ViewData(k, v) ctx.ViewData(k, v)
} }
+2 -2
View File
@@ -107,7 +107,7 @@ func GetCustomTypedPtrNilEmptyResponse() *iris.Map {
return nil return nil
} }
func GetCustomMapNilEmptyResponse() map[string]interface{} { func GetCustomMapNilEmptyResponse() map[string]any {
return nil return nil
} }
@@ -172,7 +172,7 @@ func TestFuncResult(t *testing.T) {
ContentType("text/html", "utf-8"). ContentType("text/html", "utf-8").
Body().IsEqual("<b>internal server error</b>") Body().IsEqual("<b>internal server error</b>")
expectedResultFromCustomStruct := map[string]interface{}{ expectedResultFromCustomStruct := map[string]any{
"name": "Iris", "name": "Iris",
"age": 2, "age": 2,
} }
+3 -3
View File
@@ -93,7 +93,7 @@ func isIrisHandlerType(typ reflect.Type) bool {
return typ == irisHandlerType || typ == irisHandlerFuncType 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 { if fn == nil {
panic("makeHandler: function is 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 { if handler, ok := fn.(context.Handler); ok {
return handler, ok return handler, ok
} }
@@ -196,7 +196,7 @@ func isHandler(fn interface{}) (context.Handler, bool) {
return nil, false 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 { if handlerWithErr, ok := fn.(func(*context.Context) error); ok {
return handlerWithErr, true return handlerWithErr, true
} }
+2 -2
View File
@@ -7,7 +7,7 @@ import (
"github.com/kataras/iris/v12/context" "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 { if val, ok := v.(reflect.Value); ok {
// check if it's already a reflect.Value. // check if it's already a reflect.Value.
return val return val
@@ -124,7 +124,7 @@ func equalTypes(binding reflect.Type, input reflect.Type) bool {
return binding.AssignableTo(input) return binding.AssignableTo(input)
} }
// dependency: func(...) interface{} { return "string" } // dependency: func(...) any { return "string" }
// expected input: string. // expected input: string.
if binding.Kind() == reflect.Interface { if binding.Kind() == reflect.Interface {
return input.AssignableTo(binding) return input.AssignableTo(binding)
+1 -1
View File
@@ -55,7 +55,7 @@ func isMarkedAsSingleton(structPtr any) bool {
return false return false
} }
func makeStruct(structPtr interface{}, c *Container, partyParamsCount int) *Struct { func makeStruct(structPtr any, c *Container, partyParamsCount int) *Struct {
v := valueOf(structPtr) v := valueOf(structPtr)
typ := v.Type() typ := v.Type()
if typ.Kind() != reflect.Ptr || indirectType(typ).Kind() != reflect.Struct { if typ.Kind() != reflect.Ptr || indirectType(typ).Kind() != reflect.Struct {