diff --git a/.travis.yml b/.travis.yml index 6e6ada55..a1912a50 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,13 +3,14 @@ os: - linux - osx go: - - "go1.9" - - "go1.10" + - 1.9.x + - 1.10.x + - 1.11.x go_import_path: github.com/kataras/iris # we disable test caching via GOCACHE=off -env: - global: - - GOCACHE=off +# env: +# global: +# - GOCACHE=off install: - go get ./... # for iris-contrib/httpexpect, kataras/golog script: diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 54e3725a..00000000 --- a/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM irisgo/cloud-native-go:latest - -ENV APPSOURCES /go/src/github.com/iris-contrib/cloud-native-go - -RUN ${APPSOURCES}/cloud-native-go \ No newline at end of file diff --git a/Dockerfile.build b/Dockerfile.build deleted file mode 100644 index 6c127b0e..00000000 --- a/Dockerfile.build +++ /dev/null @@ -1,12 +0,0 @@ -FROM golang:1.9.3-alpine - -RUN apk update && apk upgrade && apk add --no-cache bash git -RUN go get github.com/iris-contrib/cloud-native-go - -ENV SOURCES /go/src/github.com/iris-contrib/cloud-native-go -# COPY . ${SOURCES} - -RUN cd ${SOURCES} $$ CGO_ENABLED=0 go build - -ENTRYPOINT cloud-native-go -EXPOSE 8080 \ No newline at end of file diff --git a/FAQ.md b/FAQ.md index f5c8110d..1f5daf7f 100644 --- a/FAQ.md +++ b/FAQ.md @@ -30,7 +30,7 @@ More than 100 practical examples, tutorials and articles at: - https://github.com/kataras/iris/tree/master/_examples - https://github.com/iris-contrib/examples -- https://iris-go.com/v10/recipe +- https://iris-go.com/v11/recipe - https://docs.iris-go.com (in-progress) - https://godoc.org/github.com/kataras/iris diff --git a/Gopkg.lock b/Gopkg.lock index 944aae4d..64107208 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -115,12 +115,6 @@ packages = [".","terminal"] revision = "825e39f34365e7db2c9fbc3692c16220e3bd7418" -[[projects]] - branch = "v2" - name = "github.com/kataras/survey" - packages = [".","terminal","core"] - revision = "00934ae069eda15df26fa427ac393e67e239380c" - [[projects]] name = "github.com/klauspost/compress" packages = ["flate","gzip"] @@ -277,6 +271,24 @@ packages = ["."] revision = "aad8439df3bf67adb025382ee2e5f46a72fc9456" +[[projects]] + branch = "master" + name = "github.com/dgraph-io/badger" + packages = ["."] + revision = "99233d725dbdd26d156c61b2f42ae1671b794656" + +[[projects]] + branch = "master" + name = "github.com/etcd-io/bbolt" + packages = ["."] + revision = "acbc2c426a444a65e0cbfdcbb3573857bf18b465" + +[[projects]] + branch = "master" + name = "github.com/gomodule/redigo" + packages = ["internal","redis"] + revision = "2cd21d9966bf7ff9ae091419744f0b3fb0fecace" + [solve-meta] analyzer-name = "dep" analyzer-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 0226fcef..b03d8693 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -42,10 +42,6 @@ branch = "master" name = "github.com/kataras/golog" -[[constraint]] - branch = "v2" - name = "github.com/kataras/survey" - [[constraint]] name = "github.com/klauspost/compress" version = "1.2.1" @@ -80,4 +76,16 @@ [[constraint]] branch = "master" - name = "github.com/Shopify/goreferrer" \ No newline at end of file + name = "github.com/Shopify/goreferrer" + +[[constraint]] + name = "github.com/dgraph-io/badger" + version = "1.5.4" + +[[constraint]] + name = "github.com/etcd-io/bbolt" + version = "1.3.1-etcd.7" + +[[constraint]] + branch = "master" + name = "github.com/gomodule/redigo" diff --git a/HISTORY.md b/HISTORY.md index b042fd7c..9474eb4b 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -17,6 +17,174 @@ Developers are not forced to upgrade if they don't really need it. Upgrade whene **How to upgrade**: Open your command-line and execute this command: `go get -u github.com/kataras/iris` or let the automatic updater do that for you. +# Su, 21 October 2018 | v11.0.0 + +For the craziest of us, click [here](https://github.com/kataras/iris/compare/v10.7.0...v11) 🔥 to find out the commits and the code changes since our previous release. + +## Breaking changes + +- Remove the "Configurator" `WithoutVersionChecker` and the configuration field `DisableVersionChecker` +- `:int` parameter type **can accept negative numbers now**. +- `app.Macros().String/Int/Uint64/Path...RegisterFunc` should be replaced to: `app.Macros().Get("string" or "int" or "uint64" or "path" when "path" is the ":path" parameter type).RegisterFunc`, because you can now add custom macros and parameter types as well, see [here](_examples/routing/macros). +- `RegisterFunc("min", func(paramValue string) bool {...})` should be replaced to `RegisterFunc("min", func(paramValue ) bool {...})`, the `paramValue` argument is now stored in the exact type the macro's type evaluator inits it, i.e `uint64` or `int` and so on, therefore you don't have to convert the parameter value each time (this should make your handlers with macro functions activated even faster now) +- The `Context#ReadForm` will no longer return an error if it has no value to read from the request, we let those checks to the caller and validators as requested at: https://github.com/kataras/iris/issues/1095 by [@haritsfahreza](https://github.com/haritsfahreza) + +## Routing + +I wrote a [new router implementation](https://github.com/kataras/muxie#philosophy) for our Iris internal(low-level) routing mechanism, it is good to know that this was the second time we have updated the router internals without a single breaking change after the v6, thanks to the very well-writen and designed-first code we have for the high-level path syntax component called [macro interpreter](macro/interpreter). + +The new router supports things like **closest wildcard resolution**. + +> If the name doesn't sound good to you it is because I named that feature myself, I don't know any other framework or router that supports a thing like that so be gentle:) + +Previously you couldn't register routes like: `/{myparam:path}` and `/static` and `/{myparam:string}` and `/{myparam:string}/static` and `/static/{myparam:string}` all in one path prefix without a "decision handler". And generally if you had a wildcard it was possible to add (a single) static part and (a single) named parameter but not without performance cost and limits, why only one? (one is better than nothing: look the Iris' alternatives) We struggle to overcome our own selves, now you **can definitely do it without a bit of performance cost**, and surely we hand't imagine the wildcard to **catch all if nothing else found** without huge routing performance cost, the wildcard(`:path`) meant ONLY: "accept one or more path segments and put them into the declared parameter" so if you had register a dynamic single-path-segment named parameter like `:string, :int, :uint, :alphabetical...` in between those path segments it wouldn't work. The **closest wildcard resolution** offers you the opportunity to design your APIs even better via custom handlers and error handlers like `404 not found` to path prefixes for your API's groups, now you can do it without any custom code for path resolution inside a "decision handler" or a middleware. + +Code worths 1000 words, now it is possible to define your routes like this without any issues: + +```go +package main + +import ( + "github.com/kataras/iris" + "github.com/kataras/iris/context" +) + +func main() { + app := iris.New() + + // matches everyhing if nothing else found, + // so you can use it for custom 404 root-level/main pages! + app.Get("/{p:path}", func(ctx context.Context) { + path := ctx.Params().Get("p") + // gives the path without the first "/". + ctx.Writef("Site Custom 404 Error Message\nPage of: '%s' not found", path) + }) + + app.Get("/", indexHandler) + + // request: http://localhost:8080/profile + // response: "Profile Index" + app.Get("/profile", func(ctx context.Context) { + ctx.Writef("Profile Index") + }) + + // request: http://localhost:8080/profile/kataras + // response: "Profile of username: 'kataras'" + app.Get("/profile/{username}", func(ctx context.Context) { + username := ctx.Params().Get("username") + ctx.Writef("Profile of username: '%s'", username) + }) + + // request: http://localhost:8080/profile/settings + // response: "Profile personal settings" + app.Get("/profile/settings", func(ctx context.Context) { + ctx.Writef("Profile personal settings") + }) + + // request: http://localhost:8080/profile/settings/security + // response: "Profile personal security settings" + app.Get("/profile/settings/security", func(ctx context.Context) { + ctx.Writef("Profile personal security settings") + }) + + // matches everyhing /profile/*somethng_here* + // if no other route matches the path semgnet after the + // /profile or /profile/ + // + // So, you can use it for custom 404 profile pages + // side-by-side to your root wildcard without issues! + // For example: + // request: http://localhost:8080/profile/kataras/what + // response: + // Profile Page Custom 404 Error Message + // Profile Page of: 'kataras/what' was unable to be found + app.Get("/profile/{p:path}", func(ctx context.Context) { + path := ctx.Params().Get("p") + ctx.Writef("Profile Page Custom 404 Error Message\nProfile Page of: '%s' not found", path) + }) + + app.Run(iris.Addr(":8080")) +} + +func indexHandler(ctx context.Context) { + ctx.HTML("This is the index page") +} + +``` + +The `github.com/kataras/iris/core/router.AllMethods` is now a variable that can be altered by end-developers, so things like `app.Any` can register to custom methods as well, as requested at: https://github.com/kataras/iris/issues/1102. For example, import that package and do `router.AllMethods = append(router.AllMethods, "LINK")` in your `main` or `init` function. + +The old `github.com/kataras/iris/core/router/macro` package was moved to `guthub.com/kataras/iris/macro` to allow end-developers to add custom parameter types and macros, it supports all go standard types by default as you will see below. + +- `:int` parameter type as an alias to the old `:int` which can accept any numeric path segment now, both negative and positive numbers +- Add `:int8` parameter type and `ctx.Params().GetInt8` +- Add `:int16` parameter type and `ctx.Params().GetInt16` +- Add `:int32` parameter type and `ctx.Params().GetInt32` +- Add `:int64` parameter type and `ctx.Params().GetInt64` +- Add `:uint` parameter type and `ctx.Params().GetUint` +- Add `:uint8` parameter type and `ctx.Params().GetUint8` +- Add `:uint16` parameter type and `ctx.Params().GetUint16` +- Add `:uint32` parameter type and `ctx.Params().GetUint32` +- Add `:uint64` parameter type and `ctx.Params().GetUint64` +- Add alias `:bool` for the `:boolean` parameter type + +Here is the full list of the built'n parameter types that we support now, including their validations/path segment rules. + +| Param Type | Go Type | Validation | Retrieve Helper | +| -----------------|------|-------------|------| +| `:string` | string | the default if param type is missing, anything (single path segment) | `Params().Get` | +| `:int` | int | -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch | `Params().GetInt` | +| `:int8` | int8 | -128 to 127 | `Params().GetInt8` | +| `:int16` | int16 | -32768 to 32767 | `Params().GetInt16` | +| `:int32` | int32 | -2147483648 to 2147483647 | `Params().GetInt32` | +| `:int64` | int64 | -9223372036854775808 to 9223372036854775807 | `Params().GetInt64` | +| `:uint` | uint | 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32), depends on the host arch | `Params().GetUint` | +| `:uint8` | uint8 | 0 to 255 | `Params().GetUint8` | +| `:uint16` | uint16 | 0 to 65535 | `Params().GetUint16` | +| `:uint32` | uint32 | 0 to 4294967295 | `Params().GetUint32` | +| `:uint64` | uint64 | 0 to 18446744073709551615 | `Params().GetUint64` | +| `:bool` | bool | "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False" | `Params().GetBool` | +| `:alphabetical` | string | lowercase or uppercase letters | `Params().Get` | +| `:file` | string | lowercase or uppercase letters, numbers, underscore (_), dash (-), point (.) and no spaces or other special characters that are not valid for filenames | `Params().Get` | +| `:path` | string | anything, can be separated by slashes (path segments) but should be the last part of the route path | `Params().Get` | + +**Usage**: + +```go +app.Get("/users/{id:uint64}", func(ctx iris.Context){ + id, _ := ctx.Params().GetUint64("id") + // [...] +}) +``` + +| Built'n Func | Param Types | +| -----------|---------------| +| `regexp`(expr string) | :string | +| `prefix`(prefix string) | :string | +| `suffix`(suffix string) | :string | +| `contains`(s string) | :string | +| `min`(minValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :string(char length), :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 | +| `max`(maxValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :string(char length), :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 | +| `range`(minValue, maxValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 | + +**Usage**: + +```go +app.Get("/profile/{name:alphabetical max(255)}", func(ctx iris.Context){ + name := ctx.Params().Get("name") + // len(name) <=255 otherwise this route will fire 404 Not Found + // and this handler will not be executed at all. +}) +``` + +## Vendoring + +- Rename the vendor `sessions/sessiondb/vendor/...bbolt` from `coreos/bbolt` to `etcd-io/bbolt` and update to v1.3.1, based on [that](https://github.com/etcd-io/bbolt/releases/tag/v1.3.1-etcd.7) +- Update the vendor `sessions/sessiondb/vendor/...badger` to v1.5.3 + +I believe it is soon to adapt the new [go modules](https://github.com/golang/go/wiki/Modules#table-of-contents) inside Iris, the new `go mod` command may change until go 1.12, it is still an experimental feature. +The [vendor](https://github.com/kataras/iris/tree/master/vendor) folder will be kept until the majority of Go developers get acquainted with the new `go modules`. The `go.mod` and `go.sum` files will come at `iris v12` (or `go 1.12`), we could do that on this version as well but I don't want to have half-things, versioning should be passed on import path as well and that is a large breaking change to go with it right now, so it will probably have a new path such as `github.com/kataras/iris/v12` based on a `git tag` like every Iris release (we are lucky here because we used semantic versioning from day zero). No folder re-structure inside the root git repository to split versions will ever happen, so backwards-compatibility for older go versions(before go 1.9.3) and iris versions will be not enabled by-default although it's easy for anyone to grab any version from older [releases](https://github.com/kataras/iris/releases) or branch and target that. + # Sat, 11 August 2018 | v10.7.0 I am overjoyed to announce stage 1 of the the Iris Web framework **10.7 stable release is now available**. @@ -228,7 +396,7 @@ For example: at [_examples/mvc/basic/main.go line 100](_examples/mvc/basic/main. - fix `APIBuilder, Party#StaticWeb` and `APIBuilder, Party#StaticEmbedded` wrong strip prefix inside children parties - keep the `iris, core/router#StaticEmbeddedHandler` and remove the `core/router/APIBuilder#StaticEmbeddedHandler`, (note the `Handler` suffix) it's global and has nothing to do with the `Party` or the `APIBuilder` -- fix high path cleaning between `{}` (we already escape those contents at the [interpreter](core/router/macro/interpreter) level but some symbols are still removed by the higher-level api builder) , i.e `\\` from the string's macro function `regex` contents as reported at [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd) +- fix high path cleaning between `{}` (we already escape those contents at the [interpreter](macro/interpreter) level but some symbols are still removed by the higher-level api builder) , i.e `\\` from the string's macro function `regex` contents as reported at [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd) - sync the `golang.org/x/sys/unix` vendor ## The most important diff --git a/HISTORY_GR.md b/HISTORY_GR.md index 30f16745..98a1c416 100644 --- a/HISTORY_GR.md +++ b/HISTORY_GR.md @@ -17,9 +17,13 @@ **Πώς να αναβαθμίσετε**: Ανοίξτε την γραμμή εντολών σας και εκτελέστε αυτήν την εντολή: `go get -u github.com/kataras/iris` ή αφήστε το αυτόματο updater να το κάνει αυτό για σας. +# Su, 21 October 2018 | v11.0.0 + +Πατήστε [εδώ](https://github.com/kataras/iris/blob/master/HISTORY.md#su-21-october-2018--v11) για να διαβάσετε στα αγγλικά τις αλλαγές και τα νέα features που φέρνει νεότερη έκδοση του Iris, version 11. + # Sat, 11 August 2018 | v10.7.0 -Είμαι στην πραγματικά ευχάριστη θέση να σας ανακοινώσω το πρώτο στάδιο της σταθερής κυκλοφορίας της έκδοσης **10.7** του Iris Web Framework. +Είμαι στην, πραγματικά, ευχάριστη θέση να σας ανακοινώσω το πρώτο στάδιο της σταθερής κυκλοφορίας της έκδοσης **10.7** του Iris Web Framework. Η έκδοση 10.7.0 είναι μέρος των [επίσημων διανομών μας](https://github.com/kataras/iris/releases). diff --git a/HISTORY_ID.md b/HISTORY_ID.md index 001bdab1..36e30885 100644 --- a/HISTORY_ID.md +++ b/HISTORY_ID.md @@ -17,6 +17,10 @@ Developers tidak diwajibkan untuk melakukan upgrade apabila mereka tidak membutu **Cara Upgrade**: Bukan command-line anda dan eksekuis perintah ini: `go get -u github.com/kataras/iris` atau biarkan updater otomatis melakukannya untuk anda. +# Su, 21 October 2018 | v11.0.0 + +This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-21-october-2018--v11) instead. + # Sat, 11 August 2018 | v10.7.0 This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#sat-11-august-2018--v1070) instead. @@ -83,7 +87,7 @@ For example: at [_examples/mvc/basic/main.go line 100](_examples/mvc/basic/main. - fix `APIBuilder, Party#StaticWeb` and `APIBuilder, Party#StaticEmbedded` wrong strip prefix inside children parties - keep the `iris, core/router#StaticEmbeddedHandler` and remove the `core/router/APIBuilder#StaticEmbeddedHandler`, (note the `Handler` suffix) it's global and has nothing to do with the `Party` or the `APIBuilder` -- fix high path cleaning between `{}` (we already escape those contents at the [interpreter](core/router/macro/interpreter) level but some symbols are still removed by the higher-level api builder) , i.e `\\` from the string's macro function `regex` contents as reported at [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd) +- fix high path cleaning between `{}` (we already escape those contents at the [interpreter](macro/interpreter) level but some symbols are still removed by the higher-level api builder) , i.e `\\` from the string's macro function `regex` contents as reported at [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd) - sync the `golang.org/x/sys/unix` vendor ## The most important diff --git a/HISTORY_ZH.md b/HISTORY_ZH.md index 674ede1a..7ee04145 100644 --- a/HISTORY_ZH.md +++ b/HISTORY_ZH.md @@ -17,6 +17,10 @@ **如何升级**: 打开命令行执行以下命令: `go get -u github.com/kataras/iris` 或者等待自动更新。 +# Su, 21 October 2018 | v11.0.0 + +This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-21-october-2018--v11) instead. + # Sat, 11 August 2018 | v10.7.0 This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#sat-11-august-2018--v1070) instead. @@ -79,7 +83,7 @@ This history entry is not translated yet to the Chinese language yet, please ref - 修正 `APIBuilder, Party#StaticWeb` 和 `APIBuilder, Party#StaticEmbedded` 子分组内的前缀错误 - 保留 `iris, core/router#StaticEmbeddedHandler` 并移除 `core/router/APIBuilder#StaticEmbeddedHandler`, (`Handler` 后缀) 这是全局性的,与 `Party` `APIBuilder` 无关。 -- 修正 路径 `{}` 中的路径清理 (我们已经在 [解释器](core/router/macro/interpreter) 级别转义了这些字符, 但是一些符号仍然被更高级别的API构建器删除) , 例如 `\\` 字符串的宏函数正则表达式内容 [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd) +- 修正 路径 `{}` 中的路径清理 (我们已经在 [解释器](macro/interpreter) 级别转义了这些字符, 但是一些符号仍然被更高级别的API构建器删除) , 例如 `\\` 字符串的宏函数正则表达式内容 [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd) - 同步 `golang.org/x/sys/unix` ## 重要变更 diff --git a/README.md b/README.md index c5b94a08..e5655639 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,8 @@ -# ⚡️ The upcoming release is in-progress - -Please stay tuned by following its changelog before its official release. Click [here](https://github.com/kataras/iris/blob/v11/HISTORY.md#whenever--v1100) to read more about the upcoming release, version 11. - -> And, for the craziest of us, click [here](https://github.com/kataras/iris/compare/v10.7.0...v11) 🔥 to find out the commits and the code changes since current v10 - # Iris Web Framework -[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://iris-go.com/v10/recipe) [![release](https://img.shields.io/badge/release%20-v10.7-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) +[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/routing%20by-example-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) Iris is a fast, simple yet fully featured and very efficient web framework for Go. @@ -119,10 +113,18 @@ func main() { | Param Type | Go Type | Validation | Retrieve Helper | | -----------------|------|-------------|------| -| `:string` | string | anything | `Params().Get` | -| `:int` | uint, uint8, uint16, uint32, uint64, int, int8, int32, int64 | positive number, no digits limit | `Params().GetInt/Int64`...| -| `:long` | int64 | -9223372036854775808 to 9223372036854775807 | `Params().GetInt64` | -| `:boolean` | bool | "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False" | `Params().GetBool` | +| `:string` | string | anything (single path segment) | `Params().Get` | +| `:int` | int | -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch | `Params().GetInt` | +| `:int8` | int8 | -128 to 127 | `Params().GetInt8` | +| `:int16` | int16 | -32768 to 32767 | `Params().GetInt16` | +| `:int32` | int32 | -2147483648 to 2147483647 | `Params().GetInt32` | +| `:int64` | int64 | -9223372036854775808 to 9223372036854775807 | `Params().GetInt64` | +| `:uint` | uint | 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32), depends on the host arch | `Params().GetUint` | +| `:uint8` | uint8 | 0 to 255 | `Params().GetUint8` | +| `:uint16` | uint16 | 0 to 65535 | `Params().GetUint16` | +| `:uint32` | uint32 | 0 to 4294967295 | `Params().GetUint32` | +| `:uint64` | uint64 | 0 to 18446744073709551615 | `Params().GetUint64` | +| `:bool` | bool | "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False" | `Params().GetBool` | | `:alphabetical` | string | lowercase or uppercase letters | `Params().Get` | | `:file` | string | lowercase or uppercase letters, numbers, underscore (_), dash (-), point (.) and no spaces or other special characters that are not valid for filenames | `Params().Get` | | `:path` | string | anything, can be separated by slashes (path segments) but should be the last part of the route path | `Params().Get` | @@ -130,8 +132,8 @@ func main() { **Usage**: ```go -app.Get("/users/{id:int64}", func(ctx iris.Context){ - id, _ := ctx.Params().GetInt64("id") +app.Get("/users/{id:uint64}", func(ctx iris.Context){ + id := ctx.Params().GetUint64Default("id", 0) // [...] }) ``` @@ -142,9 +144,9 @@ app.Get("/users/{id:int64}", func(ctx iris.Context){ | `prefix`(prefix string) | :string | | `suffix`(suffix string) | :string | | `contains`(s string) | :string | -| `min`(minValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :string(char length), :int, :int64 | -| `max`(maxValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :string(char length), :int, :int64 | -| `range`(minValue, maxValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :int, :int64 | +| `min`(minValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :string(char length), :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 | +| `max`(maxValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :string(char length), :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 | +| `range`(minValue, maxValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 | **Usage**: @@ -168,7 +170,7 @@ latLonRegex, _ := regexp.Compile(latLonExpr) // Register your custom argument-less macro function to the :string param type. // MatchString is a type of func(string) bool, so we use it as it is. -app.Macros().String.RegisterFunc("coordinate", latLonRegex.MatchString) +app.Macros().Get("string").RegisterFunc("coordinate", latLonRegex.MatchString) app.Get("/coordinates/{lat:string coordinate()}/{lon:string coordinate()}", func(ctx iris.Context) { ctx.Writef("Lat: %s | Lon: %s", ctx.Params().Get("lat"), ctx.Params().Get("lon")) @@ -179,7 +181,7 @@ Register your custom macro function which accepts two int arguments. ```go -app.Macros().String.RegisterFunc("range", func(minLength, maxLength int) func(string) bool { +app.Macros().Get("string").RegisterFunc("range", func(minLength, maxLength int) func(string) bool { return func(paramValue string) bool { return len(paramValue) >= minLength && len(paramValue) <= maxLength } @@ -195,7 +197,7 @@ app.Get("/limitchar/{name:string range(1,200) else 400}", func(ctx iris.Context) Register your custom macro function which accepts a slice of strings `[...,...]`. ```go -app.Macros().String.RegisterFunc("has", func(validNames []string) func(string) bool { +app.Macros().Get("string").RegisterFunc("has", func(validNames []string) func(string) bool { return func(paramValue string) bool { for _, validName := range validNames { if validName == paramValue { @@ -218,32 +220,32 @@ app.Get("/static_validation/{name:string has([kataras,gerasimos,maropoulos]}", f ```go func main() { - app := iris.Default() + app := iris.Default() - // This handler will match /user/john but will not match neither /user/ or /user. - app.Get("/user/{name}", func(ctx iris.Context) { - name := ctx.Params().Get("name") - ctx.Writef("Hello %s", name) - }) + // This handler will match /user/john but will not match neither /user/ or /user. + app.Get("/user/{name}", func(ctx iris.Context) { + name := ctx.Params().Get("name") + ctx.Writef("Hello %s", name) + }) - // This handler will match /users/42 - // but will not match - // neither /users or /users/. - app.Get("/users/{id:long}", func(ctx iris.Context) { - id, _ := ctx.Params().GetInt64("id") - ctx.Writef("User with ID: %d", id) - }) + // This handler will match /users/42 + // but will not match /users/-1 because uint should be bigger than zero + // neither /users or /users/. + app.Get("/users/{id:uint64}", func(ctx iris.Context) { + id := ctx.Params().GetUint64Default("id", 0) + ctx.Writef("User with ID: %d", id) + }) - // This handler will match /user/john/send - // but will not match /user/john/ - app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) { - name := ctx.Params().Get("name") - action := ctx.Params().Get("action") - message := name + " is " + action - ctx.WriteString(message) - }) + // However, this one will match /user/john/send and also /user/john/everything/else/here + // but will not match /user/john neither /user/john/. + app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) { + name := ctx.Params().Get("name") + action := ctx.Params().Get("action") + message := name + " is " + action + ctx.WriteString(message) + }) - app.Run(iris.Addr(":8080")) + app.Run(iris.Addr(":8080")) } ``` @@ -251,6 +253,7 @@ func main() { > Learn more about path parameter's types by navigating [here](_examples/routing/dynamic-path/main.go#L31). + ### Dependency Injection The package [hero](hero) contains features for binding any object or functions that `handlers` can use, these are called dependencies. @@ -592,7 +595,6 @@ func main() { app.Run( iris.Addr(":8080"), iris.WithoutBanner, - iris.WithoutVersionChecker, iris.WithoutServerError(iris.ErrServerClosed), ) } @@ -897,7 +899,7 @@ func main() { ### Testing -Iris offers an incredible support for the [httpexpect](https://github.com/iris-contrib/httpexpect), a Testing Framework for web applications. However, you are able to use the standard Go's `net/http/httptest` package as well but in this example we will use the `kataras/iris/httptest`. +Iris offers an incredible support for the [httpexpect](github.com/iris-contrib/httpexpect), a Testing Framework for web applications. However, you are able to use the standard Go's `net/http/httptest` package as well but in this example we will use the `kataras/iris/httptest`. ```go package main @@ -1004,7 +1006,7 @@ Iris, unlike others, is 100% compatible with the standards and that's why the ma ## Support -- [HISTORY](HISTORY.md#sat-11-august-2018--v1070) file is your best friend, it contains information about the latest features and changes +- [HISTORY](HISTORY.md#su-21-october-2018--v1100) file is your best friend, it contains information about the latest features and changes - Did you happen to find a bug? Post it at [github issues](https://github.com/kataras/iris/issues) - Do you have any questions or need to speak with someone experienced to solve a problem at real-time? Join us to the [community chat](https://chat.iris-go.com) - Complete our form-based user experience report by clicking [here](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link) diff --git a/README_GR.md b/README_GR.md index 8fb8f43a..7cc0640a 100644 --- a/README_GR.md +++ b/README_GR.md @@ -2,7 +2,7 @@ -[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://iris-go.com/v10/recipe) [![release](https://img.shields.io/badge/release%20-v10.7-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) +[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) Το Iris είναι ένα γρήγορο, απλό αλλά και πλήρως λειτουργικό και πολύ αποδοτικό web framework για τη Go. @@ -108,7 +108,7 @@ _Η τελευταία ενημέρωση έγινε την [Τρίτη, 21 Νο ## Υποστήριξη -- To [HISTORY](HISTORY_GR.md#sat-11-august-2018--v1070) αρχείο είναι ο καλύτερος σας φίλος, περιέχει πληροφορίες σχετικά με τις τελευταίες λειτουργίες(features) και αλλαγές +- To [HISTORY](HISTORY_GR.md#su-21-october-2018--v1100) αρχείο είναι ο καλύτερος σας φίλος, περιέχει πληροφορίες σχετικά με τις τελευταίες λειτουργίες(features) και αλλαγές - Μήπως τυχαίνει να βρήκατε κάποιο bug; Δημοσιεύστε το στα [github issues](https://github.com/kataras/iris/issues) - Έχετε οποιεσδήποτε ερωτήσεις ή πρέπει να μιλήσετε με κάποιον έμπειρο για την επίλυση ενός προβλήματος σε πραγματικό χρόνο; Ελάτε μαζί μας στην [συνομιλία κοινότητας](https://chat.iris-go.com) - Συμπληρώστε την αναφορά εμπειρίας χρήστη κάνοντας κλικ [εδώ](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link) diff --git a/README_ID.md b/README_ID.md index 1839c15c..1c0f442e 100644 --- a/README_ID.md +++ b/README_ID.md @@ -2,7 +2,7 @@ -[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://iris-go.com/v10/recipe) [![release](https://img.shields.io/badge/release%20-v10.7-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) +[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) Iris adalah web framework yang cepat, sederhana namun berfitur lengkap dan sangat efisien untuk Go. @@ -106,7 +106,7 @@ _Diperbarui pada: [Tuesday, 21 November 2017](_benchmarks/README_UNIX.md)_ ## Dukungan -- File [HISTORY](HISTORY_ID.md#sat-11-august-2018--v1070) adalah sahabat anda, file tersebut memiliki informasi terkait fitur dan perubahan terbaru +- File [HISTORY](HISTORY_ID.md#su-21-october-2018--v1100) adalah sahabat anda, file tersebut memiliki informasi terkait fitur dan perubahan terbaru - Apakah anda menemukan bug? Laporkan itu melalui [github issues](https://github.com/kataras/iris/issues) - Apakah anda memiliki pertanyaan atau butuh untuk bicara kepada seseorang yang sudah berpengalaman untuk menyelesaikan masalah secara langsung? Gabung bersama kami di [community chat](https://chat.iris-go.com) - Lengkapi laporan user-experience berbasis formulir kami dengan tekan [disini](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link) diff --git a/README_JPN.md b/README_JPN.md index e2da517d..ac0603be 100644 --- a/README_JPN.md +++ b/README_JPN.md @@ -2,7 +2,7 @@ -[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://iris-go.com/v10/recipe) [![release](https://img.shields.io/badge/release%20-v10.7-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) +[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) Irisはシンプルで高速、それにも関わらず充実した機能を有する効率的なGo言語のウェブフレームワークです。 @@ -106,7 +106,7 @@ _Updated at: [Tuesday, 21 November 2017](_benchmarks/README_UNIX.md)_ ## 支援 -- [HISTORY](HISTORY.md#sat-11-august-2018--v1070)ファイルはあなたの友人です。このファイルには、機能に関する最新の情報や変更点が記載されています。 +- [HISTORY](HISTORY.md#su-21-october-2018--v1100)ファイルはあなたの友人です。このファイルには、機能に関する最新の情報や変更点が記載されています。 - バグを発見しましたか?[github issues](https://github.com/kataras/iris/issues)に投稿をお願い致します。 - 質問がありますか?または問題を即時に解決するため、熟練者に相談する必要がありますか?[community chat](https://chat.iris-go.com)に参加しましょう。 - [here](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link)をクリックしてユーザーとしての体験を報告しましょう。 diff --git a/README_PT_BR.md b/README_PT_BR.md index cdaaf03c..22f0c4f2 100644 --- a/README_PT_BR.md +++ b/README_PT_BR.md @@ -2,7 +2,7 @@ -[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://iris-go.com/v10/recipe) [![release](https://img.shields.io/badge/release%20-v10.7-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) +[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) Iris é um framework rápido, simples porém completo e muito eficiente para a linguagem Go. @@ -106,7 +106,7 @@ _Atualizado em : [Terça, 21 de Novembro de 2017](_benchmarks/README_UNIX.md)_ ## Apoie -- [HISTORY](HISTORY.md#sat-11-august-2018--v1070) o arquivo HISTORY é o seu melhor amigo, ele contém informações sobre as últimas features e mudanças. +- [HISTORY](HISTORY.md#su-21-october-2018--v1100) o arquivo HISTORY é o seu melhor amigo, ele contém informações sobre as últimas features e mudanças. - Econtrou algum bug ? Poste-o nas [issues](https://github.com/kataras/iris/issues) - Possui alguma dúvida ou gostaria de falar com alguém experiente para resolver seu problema em tempo real ? Junte-se ao [chat da nossa comunidade](https://chat.iris-go.com). - Complete nosso formulário de experiência do usuário clicando [aqui](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link) diff --git a/README_RU.md b/README_RU.md index 201e2d98..99317d9d 100644 --- a/README_RU.md +++ b/README_RU.md @@ -2,7 +2,7 @@ -[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://iris-go.com/v10/recipe) [![release](https://img.shields.io/badge/release%20-v10.7-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) +[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) Iris - это быстрая, простая, но полнофункциональная и очень эффективная веб-платформа для Go. @@ -106,7 +106,7 @@ _Обновлено: [Вторник, 21 ноября 2017 г.](_benchmarks/READ ## Поддержка -- Файл [HISTORY](HISTORY.md#sat-11-august-2018--v1070) - ваш лучший друг, он содержит информацию о последних особенностях и всех изменениях +- Файл [HISTORY](HISTORY.md#su-21-october-2018--v1100) - ваш лучший друг, он содержит информацию о последних особенностях и всех изменениях - Вы случайно обнаружили ошибку? Опубликуйте ее на [Github вопросы](https://github.com/kataras/iris/issues) - У Вас есть какие-либо вопросы или Вам нужно поговорить с кем-то, кто бы смог решить Вашу проблему в режиме реального времени? Присоединяйтесь к нам в [чате сообщества](https://chat.iris-go.com) - Заполните наш отчет о пользовательском опыте на основе формы, нажав [здесь](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link) diff --git a/README_ZH.md b/README_ZH.md index 95721dd5..e6873a34 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -2,7 +2,7 @@ -[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://iris-go.com/v10/recipe) [![release](https://img.shields.io/badge/release%20-v10.7-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) +[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris) [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases) Iris 是一款超快、简洁高效的 Go 语言 Web开发框架。 diff --git a/VERSION b/VERSION index 729c3531..236610e0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -10.7.0:https://github.com/kataras/iris/blob/master/HISTORY.md#sat-11-august-2018--v1070 \ No newline at end of file +11.0.0:https://github.com/kataras/iris/blob/master/HISTORY.md#su-21-october-2018--v1100 \ No newline at end of file diff --git a/_benchmarks/iris-mvc-templates/main.go b/_benchmarks/iris-mvc-templates/main.go index 5601ad14..cfd46558 100644 --- a/_benchmarks/iris-mvc-templates/main.go +++ b/_benchmarks/iris-mvc-templates/main.go @@ -24,7 +24,7 @@ func main() { mvc.New(app).Handle(new(controllers.HomeController)) - app.Run(iris.Addr(":5000"), iris.WithoutVersionChecker) + app.Run(iris.Addr(":5000")) } type err struct { diff --git a/_benchmarks/iris-mvc/main.go b/_benchmarks/iris-mvc/main.go index 6ea755de..4b0e0a18 100644 --- a/_benchmarks/iris-mvc/main.go +++ b/_benchmarks/iris-mvc/main.go @@ -16,7 +16,7 @@ func main() { mvc.New(app.Party("/api/values/{id}")). Handle(new(controllers.ValuesController)) - app.Run(iris.Addr(":5000"), iris.WithoutVersionChecker) + app.Run(iris.Addr(":5000")) } // +2MB/s faster than the previous implementation, 0.4MB/s difference from the raw handlers. diff --git a/_benchmarks/iris-sessions/main.go b/_benchmarks/iris-sessions/main.go index 956cad0d..d5a34062 100644 --- a/_benchmarks/iris-sessions/main.go +++ b/_benchmarks/iris-sessions/main.go @@ -24,9 +24,7 @@ func main() { app.Delete("/del", delHandler) */ - // 24 August 2017: Iris has a built'n version updater but we don't need it - // when benchmarking... - app.Run(iris.Addr(":5000"), iris.WithoutVersionChecker) + app.Run(iris.Addr(":5000")) } // Set and Get diff --git a/_benchmarks/iris/main.go b/_benchmarks/iris/main.go index 7c1ee6e2..d9885e88 100644 --- a/_benchmarks/iris/main.go +++ b/_benchmarks/iris/main.go @@ -8,5 +8,5 @@ func main() { ctx.WriteString("value") }) - app.Run(iris.Addr(":5000"), iris.WithoutVersionChecker) + app.Run(iris.Addr(":5000")) } diff --git a/_examples/README.md b/_examples/README.md index 26530a19..fd0f4f7c 100644 --- a/_examples/README.md +++ b/_examples/README.md @@ -146,8 +146,10 @@ Navigate through examples for a better understanding. - [Custom HTTP Errors](routing/http-errors/main.go) - [Dynamic Path](routing/dynamic-path/main.go) * [root level wildcard path](routing/dynamic-path/root-wildcard/main.go) +- [Write your own custom parameter types](routing/macros/main.go) **NEW** - [Reverse routing](routing/reverse/main.go) -- [Custom wrapper](routing/custom-wrapper/main.go) +- [Custom Router (high-level)](routing/custom-high-level-router/main.go) **NEW** +- [Custom Wrapper](routing/custom-wrapper/main.go) - Custom Context * [method overriding](routing/custom-context/method-overriding/main.go) * [new implementation](routing/custom-context/new-implementation/main.go) diff --git a/_examples/README_ZH.md b/_examples/README_ZH.md index 3958a5d4..1fd80a86 100644 --- a/_examples/README_ZH.md +++ b/_examples/README_ZH.md @@ -105,7 +105,9 @@ app.Get("{root:path}", rootWildcardHandler) - [自定义 HTTP 错误](routing/http-errors/main.go) - [动态路径](routing/dynamic-path/main.go) * [根级通配符路径](routing/dynamic-path/root-wildcard/main.go) +- [Write your own custom parameter types](routing/macros/main.go) **NEW** - [反向路由](routing/reverse/main.go) +- [Custom Router (high-level)](routing/custom-high-level-router/main.go) **NEW** - [自定义包装](routing/custom-wrapper/main.go) - 自定义上下文    * [方法重写](routing/custom-context/method-overriding/main.go) diff --git a/_examples/hero/overview/main.go b/_examples/hero/overview/main.go index ac722107..efb18884 100644 --- a/_examples/hero/overview/main.go +++ b/_examples/hero/overview/main.go @@ -50,8 +50,6 @@ func main() { app.Run( // Start the web server at localhost:8080 iris.Addr("localhost:8080"), - // disables updates: - iris.WithoutVersionChecker, // skip err server closed when CTRL/CMD+C pressed: iris.WithoutServerError(iris.ErrServerClosed), // enables faster json serialization and more: diff --git a/_examples/hero/sessions/main.go b/_examples/hero/sessions/main.go index aa1f67b3..76034532 100644 --- a/_examples/hero/sessions/main.go +++ b/_examples/hero/sessions/main.go @@ -34,7 +34,6 @@ func main() { app.Run( iris.Addr(":8080"), - iris.WithoutVersionChecker, iris.WithoutServerError(iris.ErrServerClosed), ) } diff --git a/_examples/http-listening/iris-configurator-and-host-configurator/README.md b/_examples/http-listening/iris-configurator-and-host-configurator/README.md deleted file mode 100644 index 89ecb89c..00000000 --- a/_examples/http-listening/iris-configurator-and-host-configurator/README.md +++ /dev/null @@ -1,2 +0,0 @@ -A silly example for this issue: https://github.com/kataras/iris/issues/688#issuecomment-318828259. -However it seems useful and therefore is being included in the examples for everyone else. \ No newline at end of file diff --git a/_examples/http-listening/iris-configurator-and-host-configurator/counter/configurator.go b/_examples/http-listening/iris-configurator-and-host-configurator/counter/configurator.go deleted file mode 100644 index 72988303..00000000 --- a/_examples/http-listening/iris-configurator-and-host-configurator/counter/configurator.go +++ /dev/null @@ -1,30 +0,0 @@ -package counter - -import ( - "time" - - "github.com/kataras/iris" - "github.com/kataras/iris/core/host" -) - -func Configurator(app *iris.Application) { - counterValue := 0 - - go func() { - ticker := time.NewTicker(time.Second) - - for range ticker.C { - counterValue++ - } - - app.ConfigureHost(func(h *host.Supervisor) { // <- HERE: IMPORTANT - h.RegisterOnShutdown(func() { - ticker.Stop() - }) - }) // or put the ticker outside of the gofunc and put the configurator before or after the app.Get, outside of this gofunc - }() - - app.Get("/counter", func(ctx iris.Context) { - ctx.Writef("Counter value = %d", counterValue) - }) -} diff --git a/_examples/http-listening/iris-configurator-and-host-configurator/main.go b/_examples/http-listening/iris-configurator-and-host-configurator/main.go index a82d974f..f1d7ad85 100644 --- a/_examples/http-listening/iris-configurator-and-host-configurator/main.go +++ b/_examples/http-listening/iris-configurator-and-host-configurator/main.go @@ -1,14 +1,28 @@ package main import ( - "github.com/kataras/iris/_examples/http-listening/iris-configurator-and-host-configurator/counter" - "github.com/kataras/iris" ) func main() { app := iris.New() - app.Configure(counter.Configurator) - app.Run(iris.Addr(":8080")) + app.ConfigureHost(func(host *iris.Supervisor) { // <- HERE: IMPORTANT + // You can control the flow or defer something using some of the host's methods: + // host.RegisterOnError + // host.RegisterOnServe + host.RegisterOnShutdown(func() { + app.Logger().Infof("Application shutdown on signal") + }) + }) + + app.Get("/", func(ctx iris.Context) { + ctx.HTML("

Hello

\n") + }) + + app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed)) + + /* There are more easy ways to notify for global shutdown using the `iris.RegisterOnInterrupt` for default signal interrupt events. + You can even go it even further by looking at the: "graceful-shutdown" example. + */ } diff --git a/_examples/http-listening/notify-on-shutdown/main.go b/_examples/http-listening/notify-on-shutdown/main.go index 67400aa8..9a6e3709 100644 --- a/_examples/http-listening/notify-on-shutdown/main.go +++ b/_examples/http-listening/notify-on-shutdown/main.go @@ -1,11 +1,10 @@ package main import ( - stdContext "context" + "context" "time" "github.com/kataras/iris" - "github.com/kataras/iris/core/host" ) func main() { @@ -15,20 +14,20 @@ func main() { ctx.HTML("

Hello, try to refresh the page after ~10 secs

") }) - // app.ConfigureHost(configureHost) -> or pass "configureHost" as `app.Addr` argument, same result. - app.Logger().Info("Wait 10 seconds and check your terminal again") // simulate a shutdown action here... go func() { <-time.After(10 * time.Second) timeout := 5 * time.Second - ctx, cancel := stdContext.WithTimeout(stdContext.Background(), timeout) + ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // close all hosts, this will notify the callback we had register // inside the `configureHost` func. app.Shutdown(ctx) }() + // app.ConfigureHost(configureHost) -> or pass "configureHost" as `app.Addr` argument, same result. + // start the server as usual, the only difference is that // we're adding a second (optional) function // to configure the just-created host supervisor. @@ -37,9 +36,14 @@ func main() { // wait 10 seconds and check your terminal. app.Run(iris.Addr(":8080", configureHost), iris.WithoutServerError(iris.ErrServerClosed)) + /* + Or for simple cases you can just use the: + iris.RegisterOnInterrupt for global catch of the CTRL/CMD+C and OS events. + Look at the "graceful-shutdown" example for more. + */ } -func configureHost(su *host.Supervisor) { +func configureHost(su *iris.Supervisor) { // here we have full access to the host that will be created // inside the `app.Run` function or `NewHost`. // diff --git a/_examples/http_request/extract-referer/main.go b/_examples/http_request/extract-referer/main.go index 8c14e54e..3e2436c5 100644 --- a/_examples/http_request/extract-referer/main.go +++ b/_examples/http_request/extract-referer/main.go @@ -25,5 +25,5 @@ func main() { // http://localhost:8080?referer=https://twitter.com/Xinterio/status/1023566830974251008 // http://localhost:8080?referer=https://www.google.com/search?q=Top+6+golang+web+frameworks&oq=Top+6+golang+web+frameworks - app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed), iris.WithoutVersionChecker) + app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed)) } diff --git a/_examples/mvc/login/main.go b/_examples/mvc/login/main.go index 83bd350f..3d77e08a 100644 --- a/_examples/mvc/login/main.go +++ b/_examples/mvc/login/main.go @@ -79,8 +79,6 @@ func main() { app.Run( // Starts the web server at localhost:8080 iris.Addr("localhost:8080"), - // Disables the updater. - iris.WithoutVersionChecker, // Ignores err server closed log when CTRL/CMD+C pressed. iris.WithoutServerError(iris.ErrServerClosed), // Enables faster json serialization and more. diff --git a/_examples/mvc/overview/main.go b/_examples/mvc/overview/main.go index 9d7d9cf6..22013325 100644 --- a/_examples/mvc/overview/main.go +++ b/_examples/mvc/overview/main.go @@ -33,8 +33,6 @@ func main() { app.Run( // Start the web server at localhost:8080 iris.Addr("localhost:8080"), - // disables updates: - iris.WithoutVersionChecker, // skip err server closed when CTRL/CMD+C pressed: iris.WithoutServerError(iris.ErrServerClosed), // enables faster json serialization and more: diff --git a/_examples/mvc/session-controller/main.go b/_examples/mvc/session-controller/main.go index 8774d448..aa3ea051 100644 --- a/_examples/mvc/session-controller/main.go +++ b/_examples/mvc/session-controller/main.go @@ -68,5 +68,5 @@ func main() { // 3. refresh the page some times // 4. close the browser // 5. re-open the browser and re-play 2. - app.Run(iris.Addr(":8080"), iris.WithoutVersionChecker) + app.Run(iris.Addr(":8080")) } diff --git a/_examples/overview/main.go b/_examples/overview/main.go index 29e52560..d416f29e 100644 --- a/_examples/overview/main.go +++ b/_examples/overview/main.go @@ -74,7 +74,7 @@ func main() { } // Listen for incoming HTTP/1.x & HTTP/2 clients on localhost port 8080. - app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8"), iris.WithoutVersionChecker) + app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8")) } func logThisMiddleware(ctx iris.Context) { diff --git a/_examples/routing/README.md b/_examples/routing/README.md index 62cde33e..88c40db9 100644 --- a/_examples/routing/README.md +++ b/_examples/routing/README.md @@ -110,9 +110,9 @@ app := iris.New() users := app.Party("/users", myAuthMiddlewareHandler) // http://localhost:8080/users/42/profile -users.Get("/{id:int}/profile", userProfileHandler) +users.Get("/{id:uint64}/profile", userProfileHandler) // http://localhost:8080/users/messages/1 -users.Get("/inbox/{id:int}", userMessageHandler) +users.Get("/inbox/{id:uint64}", userMessageHandler) ``` The same could be also written using a function which accepts the child router(the Party). @@ -124,13 +124,13 @@ app.PartyFunc("/users", func(users iris.Party) { users.Use(myAuthMiddlewareHandler) // http://localhost:8080/users/42/profile - users.Get("/{id:int}/profile", userProfileHandler) + users.Get("/{id:uint64}/profile", userProfileHandler) // http://localhost:8080/users/messages/1 - users.Get("/inbox/{id:int}", userMessageHandler) + users.Get("/inbox/{id:uint64}", userMessageHandler) }) ``` -> `id:int` is a (typed) dynamic path parameter, learn more by scrolling down. +> `id:uint` is a (typed) dynamic path parameter, learn more by scrolling down. # Dynamic Path Parameters @@ -152,23 +152,71 @@ Standard macro types for route path parameters | {param:string} | +------------------------+ string type -anything +anything (single path segmnent) -+------------------------+ -| {param:int} | -+------------------------+ ++-------------------------------+ +| {param:int} | ++-------------------------------+ int type -only numbers (0-9) +-9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch +------------------------+ -| {param:long} | +| {param:int8} | ++------------------------+ +int8 type +-128 to 127 + ++------------------------+ +| {param:int16} | ++------------------------+ +int16 type +-32768 to 32767 + ++------------------------+ +| {param:int32} | ++------------------------+ +int32 type +-2147483648 to 2147483647 + ++------------------------+ +| {param:int64} | +------------------------+ int64 type -only numbers (0-9) +-9223372036854775808 to 9223372036854775807 +------------------------+ -| {param:boolean} | +| {param:uint} | +------------------------+ +uint type +0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32) + ++------------------------+ +| {param:uint8} | ++------------------------+ +uint8 type +0 to 255 + ++------------------------+ +| {param:uint16} | ++------------------------+ +uint16 type +0 to 65535 + ++------------------------+ +| {param:uint32} | ++------------------------+ +uint32 type +0 to 4294967295 + ++------------------------+ +| {param:uint64} | ++------------------------+ +uint64 type +0 to 18446744073709551615 + ++---------------------------------+ +| {param:bool} or {param:boolean} | ++---------------------------------+ bool type only "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False" @@ -194,8 +242,8 @@ no spaces ! or other character | {param:path} | +------------------------+ path type -anything, should be the last part, more than one path segment, -i.e: /path1/path2/path3 , ctx.Params().Get("param") == "/path1/path2/path3" +anything, should be the last part, can be more than one path segment, +i.e: "/test/*param" and request: "/test/path1/path2/path3" , ctx.Params().Get("param") == "path1/path2/path3" ``` If type is missing then parameter's type is defaulted to string, so @@ -209,18 +257,24 @@ you are able to register your own too!. Register a named path parameter function ```go -app.Macros().Int.RegisterFunc("min", func(argument int) func(paramValue string) bool { +app.Macros().Get("int").RegisterFunc("min", func(argument int) func(paramValue int) bool { // [...] - return true - // -> true means valid, false means invalid fire 404 or if "else 500" is appended to the macro syntax then internal server error. + return func(paramValue int) bool { + // -> true means valid, false means invalid fire 404 + // or if "else 500" is appended to the macro syntax then internal server error. + return true + } }) ``` -At the `func(argument ...)` you can have any standard type, it will be validated before the server starts so don't care about any performance cost there, the only thing it runs at serve time is the returning `func(paramValue string) bool`. +At the `func(argument ...)` you can have any standard type, it will be validated before the server starts so don't care about any performance cost there, the only thing it runs at serve time is the returning `func(paramValue ) bool`. ```go -{param:string equal(iris)} , "iris" will be the argument here: -app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool { +{param:string equal(iris)} +``` +The "iris" will be the argument here: +```go +app.Macros().Get("string").RegisterFunc("equal", func(argument string) func(paramValue string) bool { return func(paramValue string){ return argument == paramValue } }) ``` @@ -237,38 +291,34 @@ app.Get("/username/{name}", func(ctx iris.Context) { // Let's register our first macro attached to int macro type. // "min" = the function // "minValue" = the argument of the function -// func(string) bool = the macro's path parameter evaluator, this executes in serve time when +// func() bool = the macro's path parameter evaluator, this executes in serve time when // a user requests a path which contains the :int macro type with the min(...) macro parameter function. -app.Macros().Int.RegisterFunc("min", func(minValue int) func(string) bool { +app.Macros().Get("int").RegisterFunc("min", func(minValue int) func(int) bool { // do anything before serve here [...] // at this case we don't need to do anything - return func(paramValue string) bool { - n, err := strconv.Atoi(paramValue) - if err != nil { - return false - } - return n >= minValue + return func(paramValue int) bool { + return paramValue >= minValue } }) // http://localhost:8080/profile/id>=1 // this will throw 404 even if it's found as route on : /profile/0, /profile/blabla, /profile/-1 // macro parameter functions are optional of course. -app.Get("/profile/{id:int min(1)}", func(ctx iris.Context) { +app.Get("/profile/{id:uint64 min(1)}", func(ctx iris.Context) { // second parameter is the error but it will always nil because we use macros, // the validaton already happened. - id, _ := ctx.Params().GetInt("id") + id, _ := ctx.Params().GetUint64("id") ctx.Writef("Hello id: %d", id) }) // to change the error code per route's macro evaluator: -app.Get("/profile/{id:int min(1)}/friends/{friendid:int min(1) else 504}", func(ctx iris.Context) { - id, _ := ctx.Params().GetInt("id") - friendid, _ := ctx.Params().GetInt("friendid") +app.Get("/profile/{id:uint64 min(1)}/friends/{friendid:uint64 min(1) else 504}", func(ctx iris.Context) { + id, _ := ctx.Params().GetUint64("id") + friendid, _ := ctx.Params().GetUint64("friendid") ctx.Writef("Hello id: %d looking for friend id: ", id, friendid) }) // this will throw e 504 error code instead of 404 if all route's macros not passed. -// http://localhost:8080/game/a-zA-Z/level/0-9 +// http://localhost:8080/game/a-zA-Z/level/42 // remember, alphabetical is lowercase or uppercase letters only. app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx iris.Context) { ctx.Writef("name: %s | level: %s", ctx.Params().Get("name"), ctx.Params().Get("level")) @@ -297,12 +347,10 @@ app.Run(iris.Addr(":8080")) } ``` -A **path parameter name should contain only alphabetical letters. Symbols like '_' and numbers are NOT allowed**. - +A path parameter name should contain only alphabetical letters or digits. Symbols like '_' are NOT allowed. Last, do not confuse `ctx.Params()` with `ctx.Values()`. -Path parameter's values goes to `ctx.Params()` and context's local storage -that can be used to communicate between handlers and middleware(s) goes to -`ctx.Values()`. +Path parameter's values can be retrieved from `ctx.Params()`, +context's local storage that can be used to communicate between handlers and middleware(s) can be stored to `ctx.Values()`. # Routing and reverse lookups @@ -776,6 +824,32 @@ type Context interface { // IsStopped checks and returns true if the current position of the Context is 255, // means that the StopExecution() was called. IsStopped() bool + // OnConnectionClose registers the "cb" function which will fire (on its own goroutine, no need to be registered goroutine by the end-dev) + // when the underlying connection has gone away. + // + // This mechanism can be used to cancel long operations on the server + // if the client has disconnected before the response is ready. + // + // It depends on the `http#CloseNotify`. + // CloseNotify may wait to notify until Request.Body has been + // fully read. + // + // After the main Handler has returned, there is no guarantee + // that the channel receives a value. + // + // Finally, it reports whether the protocol supports pipelines (HTTP/1.1 with pipelines disabled is not supported). + // The "cb" will not fire for sure if the output value is false. + // + // Note that you can register only one callback for the entire request handler chain/per route. + // + // Look the `ResponseWriter#CloseNotifier` for more. + OnConnectionClose(fnGoroutine func()) bool + // OnClose registers the callback function "cb" to the underline connection closing event using the `Context#OnConnectionClose` + // and also in the end of the request handler using the `ResponseWriter#SetBeforeFlush`. + // Note that you can register only one callback for the entire request handler chain/per route. + // + // Look the `Context#OnConnectionClose` and `ResponseWriter#SetBeforeFlush` for more. + OnClose(cb func()) // +------------------------------------------------------------+ // | Current "user/request" storage | @@ -855,8 +929,12 @@ type Context interface { // // Keep note that this checks the "User-Agent" request header. IsMobile() bool + // GetReferrer extracts and returns the information from the "Referer" header as specified + // in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy + // or by the URL query parameter "referer". + GetReferrer() Referrer // +------------------------------------------------------------+ - // | Response Headers helpers | + // | Headers helpers | // +------------------------------------------------------------+ // Header adds a header to the response writer. @@ -867,16 +945,18 @@ type Context interface { // GetContentType returns the response writer's header value of "Content-Type" // which may, setted before with the 'ContentType'. GetContentType() string + // GetContentType returns the request's header value of "Content-Type". + GetContentTypeRequested() string // GetContentLength returns the request's header value of "Content-Length". // Returns 0 if header was unable to be found or its value was not a valid number. GetContentLength() int64 // StatusCode sets the status code header to the response. - // Look .GetStatusCode too. + // Look .`GetStatusCode` too. StatusCode(statusCode int) // GetStatusCode returns the current status code of the response. - // Look StatusCode too. + // Look `StatusCode` too. GetStatusCode() int // Redirect sends a redirect response to the client @@ -911,6 +991,9 @@ type Context interface { // URLParamIntDefault returns the url query parameter as int value from a request, // if not found or parse failed then "def" is returned. URLParamIntDefault(name string, def int) int + // URLParamInt32Default returns the url query parameter as int32 value from a request, + // if not found or parse failed then "def" is returned. + URLParamInt32Default(name string, def int32) int32 // URLParamInt64 returns the url query parameter as int64 value from a request, // returns -1 and an error if parse failed. URLParamInt64(name string) (int64, error) @@ -1058,6 +1141,10 @@ type Context interface { // Examples of usage: context.ReadJSON, context.ReadXML. // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-custom-via-unmarshaler/main.go + // + // UnmarshalBody does not check about gzipped data. + // Do not rely on compressed data incoming to your server. The main reason is: https://en.wikipedia.org/wiki/Zip_bomb + // However you are still free to read the `ctx.Request().Body io.Reader` manually. UnmarshalBody(outPtr interface{}, unmarshaler Unmarshaler) error // ReadJSON reads JSON from request's body and binds it to a pointer of a value of any json-valid type. // @@ -1068,7 +1155,8 @@ type Context interface { // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-xml/main.go ReadXML(xmlObjectPtr interface{}) error // ReadForm binds the formObject with the form data - // it supports any kind of struct. + // it supports any kind of type, including custom structs. + // It will return nothing if request data are empty. // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-form/main.go ReadForm(formObjectPtr interface{}) error diff --git a/_examples/routing/basic/main.go b/_examples/routing/basic/main.go index d694b20c..d03ea46c 100644 --- a/_examples/routing/basic/main.go +++ b/_examples/routing/basic/main.go @@ -29,12 +29,12 @@ func main() { app.Get("/donate", donateHandler, donateFinishHandler) // Pssst, don't forget dynamic-path example for more "magic"! - app.Get("/api/users/{userid:int min(1)}", func(ctx iris.Context) { - userID, err := ctx.Params().GetInt("userid") + app.Get("/api/users/{userid:uint64 min(1)}", func(ctx iris.Context) { + userID, err := ctx.Params().GetUint64("userid") if err != nil { ctx.Writef("error while trying to parse userid parameter," + - "this will never happen if :int is being used because if it's not integer it will fire Not Found automatically.") + "this will never happen if :uint64 is being used because if it's not a valid uint64 it will fire Not Found automatically.") ctx.StatusCode(iris.StatusBadRequest) return } diff --git a/_examples/routing/custom-high-level-router/main.go b/_examples/routing/custom-high-level-router/main.go new file mode 100644 index 00000000..77830024 --- /dev/null +++ b/_examples/routing/custom-high-level-router/main.go @@ -0,0 +1,103 @@ +package main + +import ( + "strings" + + "github.com/kataras/iris" + "github.com/kataras/iris/context" + "github.com/kataras/iris/core/router" +) + +/* A Router should contain all three of the following methods: + - HandleRequest should handle the request based on the Context. + HandleRequest(ctx context.Context) + - Build should builds the handler, it's being called on router's BuildRouter. + Build(provider router.RoutesProvider) error + - RouteExists reports whether a particular route exists. + RouteExists(ctx context.Context, method, path string) bool + +For a more detailed, complete and useful example +you can take a look at the iris' router itself which is located at: +https://github.com/kataras/iris/tree/master/core/router/handler.go +which completes this exact interface, the `router#RequestHandler`. +*/ +type customRouter struct { + // a copy of routes (safer because you will not be able to alter a route on serve-time without a `app.RefreshRouter` call): + // []router.Route + // or just expect the whole routes provider: + provider router.RoutesProvider +} + +// HandleRequest a silly example which finds routes based only on the first part of the requested path +// which must be a static one as well, the rest goes to fill the parameters. +func (r *customRouter) HandleRequest(ctx context.Context) { + path := ctx.Path() + ctx.Application().Logger().Infof("Requested resource path: %s", path) + + parts := strings.Split(path, "/")[1:] + staticPath := "/" + parts[0] + for _, route := range r.provider.GetRoutes() { + if strings.HasPrefix(route.Path, staticPath) && route.Method == ctx.Method() { + paramParts := parts[1:] + for _, paramValue := range paramParts { + for _, p := range route.Tmpl().Params { + ctx.Params().Set(p.Name, paramValue) + } + } + + ctx.SetCurrentRouteName(route.Name) + ctx.Do(route.Handlers) + return + } + } + + // if nothing found... + ctx.StatusCode(iris.StatusNotFound) +} + +func (r *customRouter) Build(provider router.RoutesProvider) error { + for _, route := range provider.GetRoutes() { + // do any necessary validation or conversations based on your custom logic here + // but always run the "BuildHandlers" for each registered route. + route.BuildHandlers() + // [...] r.routes = append(r.routes, *route) + } + + r.provider = provider + return nil +} + +func (r *customRouter) RouteExists(ctx context.Context, method, path string) bool { + // [...] + return false +} + +func main() { + app := iris.New() + + // In case you are wondering, the parameter types and macros like "{param:string $func()}" still work inside + // your custom router if you fetch by the Route's Handler + // because they are middlewares under the hood, so you don't have to implement the logic of handling them manually, + // though you have to match what requested path is what route and fill the ctx.Params(), this is the work of your custom router. + app.Get("/hello/{name}", func(ctx context.Context) { + name := ctx.Params().Get("name") + ctx.Writef("Hello %s\n", name) + }) + + app.Get("/cs/{num:uint64 min(10) else 400}", func(ctx context.Context) { + num := ctx.Params().GetUint64Default("num", 0) + ctx.Writef("num is: %d\n", num) + }) + + // To replace the existing router with a customized one by using the iris/context.Context + // you have to use the `app.BuildRouter` method before `app.Run` and after the routes registered. + // You should pass your custom router's instance as the second input arg, which must completes the `router#RequestHandler` + // interface as shown above. + // + // To see how you can build something even more low-level without direct iris' context support (you can do that manually as well) + // navigate to the "custom-wrapper" example instead. + myCustomRouter := new(customRouter) + app.BuildRouter(app.ContextPool, myCustomRouter, app.APIBuilder, true) + + app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed)) +} diff --git a/_examples/routing/dynamic-path/main.go b/_examples/routing/dynamic-path/main.go index 5a3f0b57..d94b0c18 100644 --- a/_examples/routing/dynamic-path/main.go +++ b/_examples/routing/dynamic-path/main.go @@ -2,7 +2,6 @@ package main import ( "regexp" - "strconv" "github.com/kataras/iris" ) @@ -14,15 +13,14 @@ func main() { // we've seen static routes, group of routes, subdomains, wildcard subdomains, a small example of parameterized path // with a single known paramete and custom http errors, now it's time to see wildcard parameters and macros. - // iris, like net/http std package registers route's handlers + // Iris, like net/http std package registers route's handlers // by a Handler, the iris' type of handler is just a func(ctx iris.Context) // where context comes from github.com/kataras/iris/context. - // Until go 1.9 you will have to import that package too, after go 1.9 this will be not be necessary. // - // iris has the easiest and the most powerful routing process you have ever meet. + // Iris has the easiest and the most powerful routing process you have ever meet. // // At the same time, - // iris has its own interpeter(yes like a programming language) + // Iris has its own interpeter(yes like a programming language) // for route's path syntax and their dynamic path parameters parsing and evaluation, // We call them "macros" for shortcut. // How? It calculates its needs and if not any special regexp needed then it just @@ -36,21 +34,34 @@ func main() { // string type // anything // - // +------------------------+ - // | {param:int} | - // +------------------------+ + // +-------------------------------+ + // | {param:int} or {param:int} | + // +-------------------------------+ // int type - // only numbers (0-9) + // both positive and negative numbers, any number of digits (ctx.Params().GetInt will limit the digits based on the host arch) // - // +------------------------+ - // | {param:long} | - // +------------------------+ + // +-------------------------------+ + // | {param:int64} or {param:long} | + // +-------------------------------+ // int64 type - // only numbers (0-9) + // -9223372036854775808 to 9223372036854775807 // // +------------------------+ - // | {param:boolean} | + // | {param:uint8} | // +------------------------+ + // uint8 type + // 0 to 255 + // + // + // +------------------------+ + // | {param:uint64} | + // +------------------------+ + // uint64 type + // 0 to 18446744073709551615 + // + // +---------------------------------+ + // | {param:bool} or {param:boolean} | + // +---------------------------------+ // bool type // only "1" or "t" or "T" or "TRUE" or "true" or "True" // or "0" or "f" or "F" or "FALSE" or "false" or "False" @@ -89,7 +100,7 @@ func main() { // you are able to register your own too!. // // Register a named path parameter function: - // app.Macros().Int.RegisterFunc("min", func(argument int) func(paramValue string) bool { + // app.Macros().Number.RegisterFunc("min", func(argument int) func(paramValue string) bool { // [...] // return true/false -> true means valid. // }) @@ -107,51 +118,52 @@ func main() { ctx.Writef("Hello %s", ctx.Params().Get("name")) }) // type is missing = {name:string} - // Let's register our first macro attached to int macro type. + // Let's register our first macro attached to uint64 macro type. // "min" = the function // "minValue" = the argument of the function - // func(string) bool = the macro's path parameter evaluator, this executes in serve time when - // a user requests a path which contains the :int macro type with the min(...) macro parameter function. - app.Macros().Int.RegisterFunc("min", func(minValue int) func(string) bool { - // do anything before serve here [...] - // at this case we don't need to do anything - return func(paramValue string) bool { - n, err := strconv.Atoi(paramValue) - if err != nil { - return false - } - return n >= minValue + // func(uint64) bool = our func's evaluator, this executes in serve time when + // a user requests a path which contains the :uint64 macro parameter type with the min(...) macro parameter function. + app.Macros().Get("uint64").RegisterFunc("min", func(minValue uint64) func(uint64) bool { + // type of "paramValue" should match the type of the internal macro's evaluator function, which in this case is "uint64". + return func(paramValue uint64) bool { + return paramValue >= minValue } }) - // http://localhost:8080/profile/id>=1 + // http://localhost:8080/profile/id>=20 // this will throw 404 even if it's found as route on : /profile/0, /profile/blabla, /profile/-1 // macro parameter functions are optional of course. - app.Get("/profile/{id:int min(1)}", func(ctx iris.Context) { + app.Get("/profile/{id:uint64 min(20)}", func(ctx iris.Context) { // second parameter is the error but it will always nil because we use macros, // the validaton already happened. - id, _ := ctx.Params().GetInt("id") + id := ctx.Params().GetUint64Default("id", 0) ctx.Writef("Hello id: %d", id) }) // to change the error code per route's macro evaluator: - app.Get("/profile/{id:int min(1)}/friends/{friendid:int min(1) else 504}", func(ctx iris.Context) { - id, _ := ctx.Params().GetInt("id") - friendid, _ := ctx.Params().GetInt("friendid") + app.Get("/profile/{id:uint64 min(1)}/friends/{friendid:uint64 min(1) else 504}", func(ctx iris.Context) { + id := ctx.Params().GetUint64Default("id", 0) + friendid := ctx.Params().GetUint64Default("friendid", 0) ctx.Writef("Hello id: %d looking for friend id: ", id, friendid) }) // this will throw e 504 error code instead of 404 if all route's macros not passed. - // Another example using a custom regexp and any custom logic. + // :uint8 0 to 255. + app.Get("/ages/{age:uint8 else 400}", func(ctx iris.Context) { + age, _ := ctx.Params().GetUint8("age") + ctx.Writef("age selected: %d", age) + }) + + // Another example using a custom regexp or any custom logic. + + // Register your custom argument-less macro function to the :string param type. latLonExpr := "^-?[0-9]{1,3}(?:\\.[0-9]{1,10})?$" latLonRegex, err := regexp.Compile(latLonExpr) if err != nil { panic(err) } - app.Macros().String.RegisterFunc("coordinate", func() func(paramName string) (ok bool) { - // MatchString is a type of func(string) bool, so we can return that as it's. - return latLonRegex.MatchString - }) + // MatchString is a type of func(string) bool, so we use it as it is. + app.Macros().Get("string").RegisterFunc("coordinate", latLonRegex.MatchString) app.Get("/coordinates/{lat:string coordinate() else 502}/{lon:string coordinate() else 502}", func(ctx iris.Context) { ctx.Writef("Lat: %s | Lon: %s", ctx.Params().Get("lat"), ctx.Params().Get("lon")) @@ -159,7 +171,43 @@ func main() { // - // http://localhost:8080/game/a-zA-Z/level/0-9 + // Another one is by using a custom body. + app.Macros().Get("string").RegisterFunc("range", func(minLength, maxLength int) func(string) bool { + return func(paramValue string) bool { + return len(paramValue) >= minLength && len(paramValue) <= maxLength + } + }) + + app.Get("/limitchar/{name:string range(1,200)}", func(ctx iris.Context) { + name := ctx.Params().Get("name") + ctx.Writef(`Hello %s | the name should be between 1 and 200 characters length + otherwise this handler will not be executed`, name) + }) + + // + + // Register your custom macro function which accepts a slice of strings `[...,...]`. + app.Macros().Get("string").RegisterFunc("has", func(validNames []string) func(string) bool { + return func(paramValue string) bool { + for _, validName := range validNames { + if validName == paramValue { + return true + } + } + + return false + } + }) + + app.Get("/static_validation/{name:string has([kataras,gerasimos,maropoulos]}", func(ctx iris.Context) { + name := ctx.Params().Get("name") + ctx.Writef(`Hello %s | the name should be "kataras" or "gerasimos" or "maropoulos" + otherwise this handler will not be executed`, name) + }) + + // + + // http://localhost:8080/game/a-zA-Z/level/42 // remember, alphabetical is lowercase or uppercase letters only. app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx iris.Context) { ctx.Writef("name: %s | level: %s", ctx.Params().Get("name"), ctx.Params().Get("level")) @@ -197,10 +245,9 @@ func main() { // if "/mypath/{myparam:path}" then the parameter has two names, one is the "*" and the other is the user-defined "myparam". // WARNING: - // A path parameter name should contain only alphabetical letters. Symbols like '_' and numbers are NOT allowed. + // A path parameter name should contain only alphabetical letters or digits. Symbols like '_' are NOT allowed. // Last, do not confuse `ctx.Params()` with `ctx.Values()`. - // Path parameter's values goes to `ctx.Params()` and context's local storage - // that can be used to communicate between handlers and middleware(s) goes to - // `ctx.Values()`. + // Path parameter's values can be retrieved from `ctx.Params()`, + // context's local storage that can be used to communicate between handlers and middleware(s) can be stored to `ctx.Values()`. app.Run(iris.Addr(":8080")) } diff --git a/_examples/routing/macros/main.go b/_examples/routing/macros/main.go new file mode 100644 index 00000000..3de4e29a --- /dev/null +++ b/_examples/routing/macros/main.go @@ -0,0 +1,76 @@ +// Package main shows how you can register a custom parameter type and macro functions that belongs to it. +package main + +import ( + "fmt" + "reflect" + "sort" + "strings" + + "github.com/kataras/iris" + "github.com/kataras/iris/context" + "github.com/kataras/iris/hero" +) + +func main() { + app := iris.New() + app.Logger().SetLevel("debug") + + app.Macros().Register("slice", "", false, true, func(paramValue string) (interface{}, bool) { + return strings.Split(paramValue, "/"), true + }).RegisterFunc("contains", func(expectedItems []string) func(paramValue []string) bool { + sort.Strings(expectedItems) + return func(paramValue []string) bool { + if len(paramValue) != len(expectedItems) { + return false + } + + sort.Strings(paramValue) + for i := 0; i < len(paramValue); i++ { + if paramValue[i] != expectedItems[i] { + return false + } + } + + return true + } + }) + + // In order to use your new param type inside MVC controller's function input argument or a hero function input argument + // you have to tell the Iris what type it is, the `ValueRaw` of the parameter is the same type + // as you defined it above with the func(paramValue string) (interface{}, bool). + // The new value and its type(from string to your new custom type) it is stored only once now, + // you don't have to do any conversions for simple cases like this. + context.ParamResolvers[reflect.TypeOf([]string{})] = func(paramIndex int) interface{} { + return func(ctx context.Context) []string { + // When you want to retrieve a parameter with a value type that it is not supported by-default, such as ctx.Params().GetInt + // then you can use the `GetEntry` or `GetEntryAt` and cast its underline `ValueRaw` to the desired type. + // The type should be the same as the macro's evaluator function (last argument on the Macros#Register) return value. + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.([]string) + } + } + + /* + http://localhost:8080/test_slice_hero/myvaluei1/myavlue2 -> + myparam's value (a trailing path parameter type) is: []string{"myvaluei1", "myavlue2"} + */ + app.Get("/test_slice_hero/{myparam:slice}", hero.Handler(func(myparam []string) string { + return fmt.Sprintf("myparam's value (a trailing path parameter type) is: %#v\n", myparam) + })) + + /* + http://localhost:8080/test_slice_contains/notcontains1/value2 -> + (404) Not Found + + http://localhost:8080/test_slice_contains/value1/value2 -> + myparam's value (a trailing path parameter type) is: []string{"value1", "value2"} + */ + app.Get("/test_slice_contains/{myparam:slice contains([value1,value2])}", func(ctx context.Context) { + // When it is not a built'n function available to retrieve your value with the type you want, such as ctx.Params().GetInt + // then you can use the `GetEntry.ValueRaw` to get the real value, which is set-ed by your macro above. + myparam := ctx.Params().GetEntry("myparam").ValueRaw.([]string) + ctx.Writef("myparam's value (a trailing path parameter type) is: %#v\n", myparam) + }) + + app.Run(iris.Addr(":8080")) +} diff --git a/_examples/routing/main.go b/_examples/routing/main.go index d9af5f3d..9f450327 100644 --- a/_examples/routing/main.go +++ b/_examples/routing/main.go @@ -35,25 +35,25 @@ func registerGamesRoutes(app *iris.Application) { { // braces are optional of course, it's just a style of code // "GET" method - games.Get("/{gameID:int}/clans", h) - games.Get("/{gameID:int}/clans/clan/{clanPublicID:int}", h) - games.Get("/{gameID:int}/clans/search", h) + games.Get("/{gameID:uint64}/clans", h) + games.Get("/{gameID:uint64}/clans/clan/{clanPublicID:uint64}", h) + games.Get("/{gameID:uint64}/clans/search", h) // "PUT" method - games.Put("/{gameID:int}/players/{clanPublicID:int}", h) - games.Put("/{gameID:int}/clans/clan/{clanPublicID:int}", h) + games.Put("/{gameID:uint64}/players/{clanPublicID:uint64}", h) + games.Put("/{gameID:uint64}/clans/clan/{clanPublicID:uint64}", h) // remember: "clanPublicID" should not be changed to other routes with the same prefix. // "POST" method - games.Post("/{gameID:int}/clans", h) - games.Post("/{gameID:int}/players", h) - games.Post("/{gameID:int}/clans/{clanPublicID:int}/leave", h) - games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/application", h) - games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/application/{action}", h) // {action} == {action:string} - games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/invitation", h) - games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/invitation/{action}", h) - games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/delete", h) - games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/promote", h) - games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/demote", h) + games.Post("/{gameID:uint64}/clans", h) + games.Post("/{gameID:uint64}/players", h) + games.Post("/{gameID:uint64}/clans/{clanPublicID:uint64}/leave", h) + games.Post("/{gameID:uint64}/clans/{clanPublicID:uint64}/memberships/application", h) + games.Post("/{gameID:uint64}/clans/{clanPublicID:uint64}/memberships/application/{action}", h) // {action} == {action:string} + games.Post("/{gameID:uint64}/clans/{clanPublicID:uint64}/memberships/invitation", h) + games.Post("/{gameID:uint64}/clans/{clanPublicID:uint64}/memberships/invitation/{action}", h) + games.Post("/{gameID:uint64}/clans/{clanPublicID:uint64}/memberships/delete", h) + games.Post("/{gameID:uint64}/clans/{clanPublicID:uint64}/memberships/promote", h) + games.Post("/{gameID:uint64}/clans/{clanPublicID:uint64}/memberships/demote", h) gamesCh := games.Party("/challenge") { diff --git a/_examples/routing/overview/main.go b/_examples/routing/overview/main.go index 65c15dc6..d2ff7178 100644 --- a/_examples/routing/overview/main.go +++ b/_examples/routing/overview/main.go @@ -68,8 +68,8 @@ func main() { // GET: http://localhost:8080/users/42 // **/users/42 and /users/help works after iris version 7.0.5** - usersRoutes.Get("/{id:int}", func(ctx iris.Context) { - id, _ := ctx.Params().GetInt("id") + usersRoutes.Get("/{id:uint64}", func(ctx iris.Context) { + id, _ := ctx.Params().GetUint64("id") ctx.Writef("get user by id: %d", id) }) @@ -80,15 +80,15 @@ func main() { }) // PUT: http://localhost:8080/users - usersRoutes.Put("/{id:int}", func(ctx iris.Context) { - id, _ := ctx.Params().GetInt("id") // or .Get to get its string represatantion. + usersRoutes.Put("/{id:uint64}", func(ctx iris.Context) { + id, _ := ctx.Params().GetUint64("id") // or .Get to get its string represatantion. username := ctx.PostValue("username") ctx.Writef("update user for id= %d and new username= %s", id, username) }) // DELETE: http://localhost:8080/users/42 - usersRoutes.Delete("/{id:int}", func(ctx iris.Context) { - id, _ := ctx.Params().GetInt("id") + usersRoutes.Delete("/{id:uint64}", func(ctx iris.Context) { + id, _ := ctx.Params().GetUint64("id") ctx.Writef("delete user by id: %d", id) }) diff --git a/_examples/subdomains/www/main.go b/_examples/subdomains/www/main.go index c41e343d..9ecfc969 100644 --- a/_examples/subdomains/www/main.go +++ b/_examples/subdomains/www/main.go @@ -13,11 +13,11 @@ func newApp() *iris.Application { app.PartyFunc("/api/users", func(r iris.Party) { r.Get("/", info) - r.Get("/{id:int}", info) + r.Get("/{id:uint64}", info) r.Post("/", info) - r.Put("/{id:int}", info) + r.Put("/{id:uint64}", info) }) /* <- same as: usersAPI := app.Party("/api/users") { // those brackets are just syntactic-sugar things. diff --git a/_examples/tutorial/url-shortener/main.go b/_examples/tutorial/url-shortener/main.go index 1516627c..7fa91123 100644 --- a/_examples/tutorial/url-shortener/main.go +++ b/_examples/tutorial/url-shortener/main.go @@ -2,7 +2,7 @@ // // Article: https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7 // -// $ go get github.com/coreos/bbolt +// $ go get github.com/etcd-io/bbolt // $ go get github.com/satori/go.uuid // $ cd $GOPATH/src/github.com/kataras/iris/_examples/tutorial/url-shortener // $ go build diff --git a/_examples/tutorial/url-shortener/store.go b/_examples/tutorial/url-shortener/store.go index 32238b09..f2b78891 100644 --- a/_examples/tutorial/url-shortener/store.go +++ b/_examples/tutorial/url-shortener/store.go @@ -3,7 +3,7 @@ package main import ( "bytes" - "github.com/coreos/bbolt" + bolt "github.com/etcd-io/bbolt" ) // Panic panics, change it if you don't want to panic on critical INITIALIZE-ONLY-ERRORS diff --git a/_examples/tutorial/vuejs-todo-mvc/README.md b/_examples/tutorial/vuejs-todo-mvc/README.md index 00c912fa..b856373b 100644 --- a/_examples/tutorial/vuejs-todo-mvc/README.md +++ b/_examples/tutorial/vuejs-todo-mvc/README.md @@ -27,7 +27,7 @@ Many articles have been written, in the past, that lead developers not to use a You’ll need two dependencies: 1. Vue.js, for our client-side requirements. Download it from [here](https://vuejs.org/), latest v2. -2. The Iris Web Framework, for our server-side requirements. Can be found [here](https://github.com/kataras/iris), latest v10. +2. The Iris Web Framework, for our server-side requirements. Can be found [here](https://github.com/kataras/iris), latest v11. > If you have Go already installed then just execute `go get -u github.com/kataras/iris` to install the Iris Web Framework. @@ -530,7 +530,7 @@ func main() { todosApp.Handle(new(controllers.TodoController)) // start the web server at http://localhost:8080 - app.Run(iris.Addr(":8080"), iris.WithoutVersionChecker) + app.Run(iris.Addr(":8080")) } ``` diff --git a/_examples/tutorial/vuejs-todo-mvc/src/web/main.go b/_examples/tutorial/vuejs-todo-mvc/src/web/main.go index c571e426..34e5ed88 100644 --- a/_examples/tutorial/vuejs-todo-mvc/src/web/main.go +++ b/_examples/tutorial/vuejs-todo-mvc/src/web/main.go @@ -51,5 +51,5 @@ func main() { todosApp.Handle(new(controllers.TodoController)) // start the web server at http://localhost:8080 - app.Run(iris.Addr(":8080"), iris.WithoutVersionChecker) + app.Run(iris.Addr(":8080")) } diff --git a/_examples/webassembly/basic/client/hello_go11beta3.go b/_examples/webassembly/basic/client/hello_go111.go similarity index 70% rename from _examples/webassembly/basic/client/hello_go11beta3.go rename to _examples/webassembly/basic/client/hello_go111.go index 9cbf5060..97dda1f5 100644 --- a/_examples/webassembly/basic/client/hello_go11beta3.go +++ b/_examples/webassembly/basic/client/hello_go111.go @@ -1,4 +1,4 @@ -// +build go1.11beta3 +// +build js package main @@ -9,7 +9,7 @@ import ( ) func main() { - // GOARCH=wasm GOOS=js /home/$yourusername/go1.11beta1/bin/go build -o hello.wasm hello_go11beta2.go + // GOARCH=wasm GOOS=js /home/$yourusername/go1.11/bin/go build -o hello.wasm hello_go111.go js.Global().Get("console").Call("log", "Hello WebAssemply!") message := fmt.Sprintf("Hello, the current time is: %s", time.Now().String()) js.Global().Get("document").Call("getElementById", "hello").Set("innerText", message) diff --git a/_examples/webassembly/basic/main.go b/_examples/webassembly/basic/main.go index 7dfe0ad2..4099da53 100644 --- a/_examples/webassembly/basic/main.go +++ b/_examples/webassembly/basic/main.go @@ -6,7 +6,7 @@ import ( /* You need to build the hello.wasm first, download the go1.11 and execute the below command: -$ cd client && GOARCH=wasm GOOS=js /home/$yourname/go1.11beta3/bin/go build -o hello.wasm hello_go11beta3.go +$ cd client && GOARCH=wasm GOOS=js /home/$yourname/go1.11/bin/go build -o hello.wasm hello_go111.go */ func main() { diff --git a/configuration.go b/configuration.go index 7bbc0139..6ee8071f 100644 --- a/configuration.go +++ b/configuration.go @@ -222,14 +222,6 @@ var WithoutInterruptHandler = func(app *Application) { app.config.DisableInterruptHandler = true } -// WithoutVersionChecker will disable the version checker and updater. -// The Iris server will be not -// receive automatic updates if you pass this -// to the `Run` function. Use it only while you're ready for Production environment. -var WithoutVersionChecker = func(app *Application) { - app.config.DisableVersionChecker = true -} - // WithoutPathCorrection disables the PathCorrection setting. // // See `Configuration`. @@ -388,11 +380,6 @@ type Configuration struct { // Defaults to false. DisableInterruptHandler bool `json:"disableInterruptHandler,omitempty" yaml:"DisableInterruptHandler" toml:"DisableInterruptHandler"` - // DisableVersionChecker if true then process will be not be notified for any available updates. - // - // Defaults to false. - DisableVersionChecker bool `json:"disableVersionChecker,omitempty" yaml:"DisableVersionChecker" toml:"DisableVersionChecker"` - // DisablePathCorrection corrects and redirects the requested path to the registered path // for example, if /home/ path is requested but no handler for this Route found, // then the Router checks if /home handler exists, if yes, @@ -677,10 +664,6 @@ func WithConfiguration(c Configuration) Configurator { main.DisableInterruptHandler = v } - if v := c.DisableVersionChecker; v { - main.DisableVersionChecker = v - } - if v := c.DisablePathCorrection; v { main.DisablePathCorrection = v } @@ -758,7 +741,6 @@ func DefaultConfiguration() Configuration { return Configuration{ DisableStartupLog: false, DisableInterruptHandler: false, - DisableVersionChecker: false, DisablePathCorrection: false, EnablePathEscape: false, FireMethodNotAllowed: false, diff --git a/configuration_test.go b/configuration_test.go index ab770fbe..913ebe84 100644 --- a/configuration_test.go +++ b/configuration_test.go @@ -77,13 +77,12 @@ func TestConfigurationOptions(t *testing.T) { func TestConfigurationOptionsDeep(t *testing.T) { charset := "MYCHARSET" - app := New().Configure(WithCharset(charset), WithoutBodyConsumptionOnUnmarshal, WithoutBanner, WithoutVersionChecker) + app := New().Configure(WithCharset(charset), WithoutBodyConsumptionOnUnmarshal, WithoutBanner) expected := DefaultConfiguration() expected.Charset = charset expected.DisableBodyConsumptionOnUnmarshal = true expected.DisableStartupLog = true - expected.DisableVersionChecker = true has := *app.config @@ -142,7 +141,6 @@ func TestConfigurationYAML(t *testing.T) { }() yamlConfigurationContents := ` -DisableVersionChecker: true DisablePathCorrection: false EnablePathEscape: false FireMethodNotAllowed: true @@ -165,10 +163,6 @@ Other: c := app.config - if expected := true; c.DisableVersionChecker != expected { - t.Fatalf("error on TestConfigurationYAML: Expected DisableVersionChecker %v but got %v", expected, c.DisableVersionChecker) - } - if expected := false; c.DisablePathCorrection != expected { t.Fatalf("error on TestConfigurationYAML: Expected DisablePathCorrection %v but got %v", expected, c.DisablePathCorrection) } @@ -241,7 +235,6 @@ func TestConfigurationTOML(t *testing.T) { }() tomlConfigurationContents := ` -DisableVersionChecker = true EnablePathEscape = false FireMethodNotAllowed = true EnableOptimizations = true @@ -265,10 +258,6 @@ Charset = "UTF-8" c := app.config - if expected := true; c.DisableVersionChecker != expected { - t.Fatalf("error on TestConfigurationTOML: Expected DisableVersionChecker %v but got %v", expected, c.DisableVersionChecker) - } - if expected := false; c.DisablePathCorrection != expected { t.Fatalf("error on TestConfigurationTOML: Expected DisablePathCorrection %v but got %v", expected, c.DisablePathCorrection) } diff --git a/context/context.go b/context/context.go index 8f2d40c6..7ea78229 100644 --- a/context/context.go +++ b/context/context.go @@ -76,131 +76,6 @@ func (u UnmarshalerFunc) Unmarshal(data []byte, v interface{}) error { return u(data, v) } -// RequestParams is a key string - value string storage which -// context's request dynamic path params are being kept. -// Empty if the route is static. -type RequestParams struct { - store memstore.Store -} - -// Set adds a key-value pair to the path parameters values -// it's being called internally so it shouldn't be used as a local storage by the user, use `ctx.Values()` instead. -func (r *RequestParams) Set(key, value string) { - r.store.Set(key, value) -} - -// Visit accepts a visitor which will be filled -// by the key-value params. -func (r *RequestParams) Visit(visitor func(key string, value string)) { - r.store.Visit(func(k string, v interface{}) { - visitor(k, v.(string)) // always string here. - }) -} - -var emptyEntry memstore.Entry - -// GetEntryAt returns the internal Entry of the memstore based on its index, -// the stored index by the router. -// If not found then it returns a zero Entry and false. -func (r RequestParams) GetEntryAt(index int) (memstore.Entry, bool) { - if len(r.store) > index { - return r.store[index], true - } - return emptyEntry, false -} - -// GetEntry returns the internal Entry of the memstore based on its "key". -// If not found then it returns a zero Entry and false. -func (r RequestParams) GetEntry(key string) (memstore.Entry, bool) { - // we don't return the pointer here, we don't want to give the end-developer - // the strength to change the entry that way. - if e := r.store.GetEntry(key); e != nil { - return *e, true - } - return emptyEntry, false -} - -// Get returns a path parameter's value based on its route's dynamic path key. -func (r RequestParams) Get(key string) string { - return r.store.GetString(key) -} - -// GetTrim returns a path parameter's value without trailing spaces based on its route's dynamic path key. -func (r RequestParams) GetTrim(key string) string { - return strings.TrimSpace(r.Get(key)) -} - -// GetEscape returns a path parameter's double-url-query-escaped value based on its route's dynamic path key. -func (r RequestParams) GetEscape(key string) string { - return DecodeQuery(DecodeQuery(r.Get(key))) -} - -// GetDecoded returns a path parameter's double-url-query-escaped value based on its route's dynamic path key. -// same as `GetEscape`. -func (r RequestParams) GetDecoded(key string) string { - return r.GetEscape(key) -} - -// GetInt returns the path parameter's value as int, based on its key. -// It checks for all available types of int, including int64, strings etc. -// It will return -1 and a non-nil error if parameter wasn't found. -func (r RequestParams) GetInt(key string) (int, error) { - return r.store.GetInt(key) -} - -// GetInt64 returns the path paramete's value as int64, based on its key. -// It checks for all available types of int, including int, strings etc. -// It will return -1 and a non-nil error if parameter wasn't found. -func (r RequestParams) GetInt64(key string) (int64, error) { - return r.store.GetInt64(key) -} - -// GetFloat64 returns a path parameter's value based as float64 on its route's dynamic path key. -// It checks for all available types of int, including float64, int, strings etc. -// It will return -1 and a non-nil error if parameter wasn't found. -func (r RequestParams) GetFloat64(key string) (float64, error) { - return r.store.GetFloat64(key) -} - -// GetUint64 returns the path paramete's value as uint64, based on its key. -// It checks for all available types of int, including int, uint64, int64, strings etc. -// It will return 0 and a non-nil error if parameter wasn't found. -func (r RequestParams) GetUint64(key string) (uint64, error) { - return r.store.GetUint64(key) -} - -// GetBool returns the path parameter's value as bool, based on its key. -// a string which is "1" or "t" or "T" or "TRUE" or "true" or "True" -// or "0" or "f" or "F" or "FALSE" or "false" or "False". -// Any other value returns an error. -func (r RequestParams) GetBool(key string) (bool, error) { - return r.store.GetBool(key) -} - -// GetIntUnslashed same as Get but it removes the first slash if found. -// Usage: Get an id from a wildcard path. -// -// Returns -1 with an error if the parameter couldn't be found. -func (r RequestParams) GetIntUnslashed(key string) (int, error) { - v := r.Get(key) - if v != "" { - if len(v) > 1 { - if v[0] == '/' { - v = v[1:] - } - } - return strconv.Atoi(v) - - } - - return -1, fmt.Errorf("unable to find int for '%s'", key) -} - -// Len returns the full length of the parameters. -func (r RequestParams) Len() int { - return r.store.Len() -} - // Context is the midle-man server's "object" for the clients. // // A New context is being acquired from a sync.Pool on each connection. @@ -685,7 +560,8 @@ type Context interface { // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-xml/main.go ReadXML(xmlObjectPtr interface{}) error // ReadForm binds the formObject with the form data - // it supports any kind of struct. + // it supports any kind of type, including custom structs. + // It will return nothing if request data are empty. // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-form/main.go ReadForm(formObjectPtr interface{}) error @@ -1116,7 +992,7 @@ func NewContext(app Application) Context { func (ctx *context) BeginRequest(w http.ResponseWriter, r *http.Request) { ctx.handlers = nil // will be filled by router.Serve/HTTP ctx.values = ctx.values[0:0] // >> >> by context.Values().Set - ctx.params.store = ctx.params.store[0:0] + ctx.params.Store = ctx.params.Store[0:0] ctx.request = r ctx.currentHandlerIndex = 0 ctx.writer = AcquireResponseWriter() @@ -2414,17 +2290,15 @@ var ( errReadBody = errors.New("while trying to read %s from the request body. Trace %s") ) -// ErrEmptyForm will be thrown from `context#ReadForm` when empty request data. -var ErrEmptyForm = errors.New("form data: empty") - // ReadForm binds the formObject with the form data -// it supports any kind of struct. +// it supports any kind of type, including custom structs. +// It will return nothing if request data are empty. // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-form/main.go func (ctx *context) ReadForm(formObject interface{}) error { values := ctx.FormValues() - if values == nil { - return ErrEmptyForm + if len(values) == 0 { + return nil } // or dec := formbinder.NewDecoder(&formbinder.DecoderOptions{TagName: "form"}) @@ -2990,12 +2864,10 @@ func (ctx *context) JSON(v interface{}, opts ...JSON) (n int, err error) { options = opts[0] } - optimize := ctx.shouldOptimize() - ctx.ContentType(ContentJSONHeaderValue) if options.StreamingJSON { - if optimize { + if ctx.shouldOptimize() { var jsoniterConfig = jsoniter.Config{ EscapeHTML: !options.UnescapeHTML, IndentionStep: 4, @@ -3016,7 +2888,7 @@ func (ctx *context) JSON(v interface{}, opts ...JSON) (n int, err error) { return ctx.writer.Written(), err } - n, err = WriteJSON(ctx.writer, v, options, optimize) + n, err = WriteJSON(ctx.writer, v, options, ctx.shouldOptimize()) if err != nil { ctx.StatusCode(http.StatusInternalServerError) return 0, err diff --git a/context/request_params.go b/context/request_params.go new file mode 100644 index 00000000..7757308b --- /dev/null +++ b/context/request_params.go @@ -0,0 +1,206 @@ +package context + +import ( + "fmt" + "reflect" + "strconv" + "strings" + + "github.com/kataras/iris/core/memstore" +) + +// RequestParams is a key string - value string storage which +// context's request dynamic path params are being kept. +// Empty if the route is static. +type RequestParams struct { + memstore.Store +} + +// Set inserts a value to the key-value storage. +// +// See `SetImmutable` and `Get` too. +func (r *RequestParams) Set(key, value string) { + r.Store.Set(key, value) +} + +// GetEntryAt will return the parameter's internal store's `Entry` based on the index. +// If not found it will return an emptry `Entry`. +func (r *RequestParams) GetEntryAt(index int) memstore.Entry { + entry, _ := r.Store.GetEntryAt(index) + return entry +} + +// GetEntry will return the parameter's internal store's `Entry` based on its name/key. +// If not found it will return an emptry `Entry`. +func (r *RequestParams) GetEntry(key string) memstore.Entry { + entry, _ := r.Store.GetEntry(key) + return entry +} + +// Visit accepts a visitor which will be filled +// by the key-value params. +func (r *RequestParams) Visit(visitor func(key string, value string)) { + r.Store.Visit(func(k string, v interface{}) { + visitor(k, fmt.Sprintf("%v", v)) // always string here. + }) +} + +// Get returns a path parameter's value based on its route's dynamic path key. +func (r RequestParams) Get(key string) string { + return r.GetString(key) +} + +// GetTrim returns a path parameter's value without trailing spaces based on its route's dynamic path key. +func (r RequestParams) GetTrim(key string) string { + return strings.TrimSpace(r.Get(key)) +} + +// GetEscape returns a path parameter's double-url-query-escaped value based on its route's dynamic path key. +func (r RequestParams) GetEscape(key string) string { + return DecodeQuery(DecodeQuery(r.Get(key))) +} + +// GetDecoded returns a path parameter's double-url-query-escaped value based on its route's dynamic path key. +// same as `GetEscape`. +func (r RequestParams) GetDecoded(key string) string { + return r.GetEscape(key) +} + +// GetIntUnslashed same as Get but it removes the first slash if found. +// Usage: Get an id from a wildcard path. +// +// Returns -1 and false if not path parameter with that "key" found. +func (r RequestParams) GetIntUnslashed(key string) (int, bool) { + v := r.Get(key) + if v != "" { + if len(v) > 1 { + if v[0] == '/' { + v = v[1:] + } + } + + vInt, err := strconv.Atoi(v) + if err != nil { + return -1, false + } + return vInt, true + } + + return -1, false +} + +var ( + // ParamResolvers is the global param resolution for a parameter type for a specific go std or custom type. + // + // Key is the specific type, which should be unique. + // The value is a function which accepts the parameter index + // and it should return the value as the parameter type evaluator expects it. + // i.e [reflect.TypeOf("string")] = func(paramIndex int) interface{} { + // return func(ctx Context) { + // return ctx.Params().GetEntryAt(paramIndex).ValueRaw.() + // } + // } + // + // Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details. + ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ + reflect.TypeOf(""): func(paramIndex int) interface{} { + return func(ctx Context) string { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(string) + } + }, + reflect.TypeOf(int(1)): func(paramIndex int) interface{} { + return func(ctx Context) int { + // v, _ := ctx.Params().GetEntryAt(paramIndex).IntDefault(0) + // return v + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int) + } + }, + reflect.TypeOf(int8(1)): func(paramIndex int) interface{} { + return func(ctx Context) int8 { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int8) + } + }, + reflect.TypeOf(int16(1)): func(paramIndex int) interface{} { + return func(ctx Context) int16 { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int16) + } + }, + reflect.TypeOf(int32(1)): func(paramIndex int) interface{} { + return func(ctx Context) int32 { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int32) + } + }, + reflect.TypeOf(int64(1)): func(paramIndex int) interface{} { + return func(ctx Context) int64 { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int64) + } + }, + reflect.TypeOf(uint(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint) + } + }, + reflect.TypeOf(uint8(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint8 { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint8) + } + }, + reflect.TypeOf(uint16(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint16 { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint16) + } + }, + reflect.TypeOf(uint32(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint32 { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint32) + } + }, + reflect.TypeOf(uint64(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint64 { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint64) + } + }, + reflect.TypeOf(true): func(paramIndex int) interface{} { + return func(ctx Context) bool { + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(bool) + } + }, + } +) + +// ParamResolverByTypeAndIndex will return a function that can be used to bind path parameter's exact value by its Go std type +// and the parameter's index based on the registered path. +// Usage: nameResolver := ParamResolverByKindAndKey(reflect.TypeOf(""), 0) +// Inside a Handler: nameResolver.Call(ctx)[0] +// it will return the reflect.Value Of the exact type of the parameter(based on the path parameters and macros). +// It is only useful for dynamic binding of the parameter, it is used on "hero" package and it should be modified +// only when Macros are modified in such way that the default selections for the available go std types are not enough. +// +// Returns empty value and false if "k" does not match any valid parameter resolver. +func ParamResolverByTypeAndIndex(typ reflect.Type, paramIndex int) (reflect.Value, bool) { + /* NO: + // This could work but its result is not exact type, so direct binding is not possible. + resolver := m.ParamResolver + fn := func(ctx context.Context) interface{} { + entry, _ := ctx.Params().GetEntry(paramName) + return resolver(entry) + } + // + + // This works but it is slower on serve-time. + paramNameValue := []reflect.Value{reflect.ValueOf(paramName)} + var fnSignature func(context.Context) string + return reflect.MakeFunc(reflect.ValueOf(&fnSignature).Elem().Type(), func(in []reflect.Value) []reflect.Value { + return in[0].MethodByName("Params").Call(emptyIn)[0].MethodByName("Get").Call(paramNameValue) + // return []reflect.Value{reflect.ValueOf(in[0].Interface().(context.Context).Params().Get(paramName))} + }) + // + */ + + r, ok := ParamResolvers[typ] + if !ok || r == nil { + return reflect.Value{}, false + } + + return reflect.ValueOf(r(paramIndex)), true +} diff --git a/context/route.go b/context/route.go index e632f11f..7c680e7d 100644 --- a/context/route.go +++ b/context/route.go @@ -1,6 +1,6 @@ package context -import "github.com/kataras/iris/core/router/macro" +import "github.com/kataras/iris/macro" // RouteReadOnly allows decoupled access to the current route // inside the context. @@ -25,7 +25,7 @@ type RouteReadOnly interface { // StaticPath returns the static part of the original, registered route path. // if /user/{id} it will return /user - // if /user/{id}/friend/{friendid:int} it will return /user too + // if /user/{id}/friend/{friendid:uint64} it will return /user too // if /assets/{filepath:path} it will return /assets. StaticPath() string diff --git a/core/host/proxy_test.go b/core/host/proxy_test.go index b7ad878e..76561b34 100644 --- a/core/host/proxy_test.go +++ b/core/host/proxy_test.go @@ -60,7 +60,7 @@ func TestProxy(t *testing.T) { t.Fatalf("%v while creating tcp4 listener for new tls local test listener", err) } // main server - go app.Run(iris.Listener(httptest.NewLocalTLSListener(l)), iris.WithoutVersionChecker, iris.WithoutStartupLog) + go app.Run(iris.Listener(httptest.NewLocalTLSListener(l)), iris.WithoutStartupLog) e := httptest.NewInsecure(t, httptest.URL("http://"+listener.Addr().String())) e.GET("/").Expect().Status(iris.StatusOK).Body().Equal(expectedIndex) diff --git a/core/maintenance/maintenance.go b/core/maintenance/maintenance.go deleted file mode 100644 index 613b67fd..00000000 --- a/core/maintenance/maintenance.go +++ /dev/null @@ -1,6 +0,0 @@ -package maintenance - -// Start starts the maintenance process. -func Start() { - CheckForUpdates() -} diff --git a/core/maintenance/version.go b/core/maintenance/version.go deleted file mode 100644 index f3d3113f..00000000 --- a/core/maintenance/version.go +++ /dev/null @@ -1,78 +0,0 @@ -package maintenance - -import ( - "fmt" - "os" - "os/exec" - - "github.com/kataras/iris/core/maintenance/version" - - "github.com/kataras/golog" - "github.com/kataras/survey" -) - -const ( - // Version is the string representation of the current local Iris Web Framework version. - Version = "10.7.0" -) - -// CheckForUpdates checks for any available updates -// and asks for the user if want to update now or not. -func CheckForUpdates() { - v := version.Acquire() - updateAvailale := v.Compare(Version) == version.Smaller - - if updateAvailale { - if confirmUpdate(v) { - installVersion() - return - } - } -} - -func confirmUpdate(v version.Version) bool { - // on help? when asking for installing the new update. - ignoreUpdatesMsg := "Would you like to ignore future updates? Disable the version checker via:\napp.Run(..., iris.WithoutVersionChecker)" - - // if update available ask for update action. - shouldUpdateNowMsg := - fmt.Sprintf("A new version is available online[%s > %s]. Type '?' for help.\nRelease notes: %s.\nUpdate now?", - v.String(), Version, v.ChangelogURL) - - var confirmUpdate bool - survey.AskOne(&survey.Confirm{ - Message: shouldUpdateNowMsg, - Help: ignoreUpdatesMsg, - }, &confirmUpdate, nil) - return confirmUpdate // it's true only when update was available and user typed "yes". -} - -func installVersion() { - golog.Infof("Downloading...\n") - repo := "github.com/kataras/iris/..." - cmd := exec.Command("go", "get", "-u", "-v", repo) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stdout - - if err := cmd.Run(); err != nil { - golog.Warnf("unexpected message while trying to go get,\nif you edited the original source code then you've to remove the whole $GOPATH/src/github.com/kataras folder and execute `go get -u github.com/kataras/iris/...` manually\n%v", err) - return - } - - golog.Infof("Update process finished.\nManual rebuild and restart is required to apply the changes...\n") - return -} - -/* Author's note: -We could use github webhooks to automatic notify for updates -when a new update is pushed to the repository -even when server is already started and running but this would expose -a route which dev may don't know about, so let it for now but if -they ask it then I should add an optional configuration field -to "live/realtime update" and implement the idea (which is already implemented in the iris-go server). -*/ - -/* Author's note: -The old remote endpoint for version checker is still available on the server for backwards -compatibility with older clients, it will stay there for a long period of time. -*/ diff --git a/core/maintenance/version/fetch.go b/core/maintenance/version/fetch.go deleted file mode 100644 index 82d3cd75..00000000 --- a/core/maintenance/version/fetch.go +++ /dev/null @@ -1,59 +0,0 @@ -package version - -import ( - "io/ioutil" - "strings" - "time" - - "github.com/hashicorp/go-version" - - "github.com/kataras/golog" - "github.com/kataras/iris/core/netutil" -) - -const ( - versionURL = "https://raw.githubusercontent.com/kataras/iris/master/VERSION" -) - -func fetch() (*version.Version, string) { - client := netutil.Client(time.Duration(30 * time.Second)) - - r, err := client.Get(versionURL) - if err != nil { - golog.Debugf("err: %v\n", err) - return nil, "" - } - defer r.Body.Close() - - if r.StatusCode >= 400 { - golog.Debugf("Internet connection is missing, updater is unable to fetch the latest Iris version\n%v", err) - return nil, "" - } - - b, err := ioutil.ReadAll(r.Body) - - if len(b) == 0 || err != nil { - golog.Debugf("err: %v\n", err) - return nil, "" - } - - var ( - fetchedVersion = string(b) - changelogURL string - ) - // Example output: - // Version(8.5.5) - // 8.5.5:https://github.com/kataras/iris/blob/master/HISTORY.md#tu-02-november-2017--v855 - if idx := strings.IndexByte(fetchedVersion, ':'); idx > 0 { - changelogURL = fetchedVersion[idx+1:] - fetchedVersion = fetchedVersion[0:idx] - } - - latestVersion, err := version.NewVersion(fetchedVersion) - if err != nil { - golog.Debugf("while fetching and parsing latest version from github: %v\n", err) - return nil, "" - } - - return latestVersion, changelogURL -} diff --git a/core/maintenance/version/version.go b/core/maintenance/version/version.go deleted file mode 100644 index 4a338952..00000000 --- a/core/maintenance/version/version.go +++ /dev/null @@ -1,64 +0,0 @@ -package version - -import ( - "time" - - "github.com/hashicorp/go-version" -) - -// Version is a version wrapper which -// contains some additional customized properties. -type Version struct { - version.Version - WrittenAt time.Time - ChangelogURL string -} - -// Result is the compare result type. -// Available types are Invalid, Smaller, Equal or Larger. -type Result int32 - -const ( - // Smaller when the compared version is smaller than the latest one. - Smaller Result = -1 - // Equal when the compared version is equal with the latest one. - Equal Result = 0 - // Larger when the compared version is larger than the latest one. - Larger Result = 1 - // Invalid means that an error occurred when comparing the versions. - Invalid Result = -2 -) - -// Compare compares the "versionStr" with the latest Iris version, -// opossite to the version package -// it returns the result of the "versionStr" not the "v" itself. -func (v *Version) Compare(versionStr string) Result { - if len(v.Version.String()) == 0 { - // if version not refreshed, by an internet connection lose, - // then return Invalid. - return Invalid - } - - other, err := version.NewVersion(versionStr) - if err != nil { - return Invalid - } - return Result(other.Compare(&v.Version)) -} - -// Acquire returns the latest version info wrapper. -// It calls the fetch. -func Acquire() (v Version) { - newVersion, changelogURL := fetch() - if newVersion == nil { // if github was down then don't panic, just set it as the smallest version. - newVersion, _ = version.NewVersion("0.0.1") - } - - v = Version{ - Version: *newVersion, - WrittenAt: time.Now(), - ChangelogURL: changelogURL, - } - - return -} diff --git a/core/memstore/memstore.go b/core/memstore/memstore.go index 5b6bbdf2..001762e0 100644 --- a/core/memstore/memstore.go +++ b/core/memstore/memstore.go @@ -6,6 +6,8 @@ package memstore import ( + "fmt" + "math" "reflect" "strconv" "strings" @@ -14,6 +16,11 @@ import ( ) type ( + // ValueSetter is the interface which can be accepted as a generic solution of RequestParams or memstore when Set is the only requirement, + // i.e internally on macro/template/TemplateParam#Eval:paramChanger. + ValueSetter interface { + Set(key string, newValue interface{}) (Entry, bool) + } // Entry is the entry of the context storage Store - .Values() Entry struct { Key string @@ -25,6 +32,8 @@ type ( Store []Entry ) +var _ ValueSetter = (*Store)(nil) + // GetByKindOrNil will try to get this entry's value of "k" kind, // if value is not that kind it will NOT try to convert it the "k", instead // it will return nil, except if boolean; then it will return false @@ -67,11 +76,19 @@ func (e Entry) GetByKindOrNil(k reflect.Kind) interface{} { // If not found returns "def". func (e Entry) StringDefault(def string) string { v := e.ValueRaw + if v == nil { + return def + } if vString, ok := v.(string); ok { return vString } + val := fmt.Sprintf("%v", v) + if val != "" { + return val + } + return def } @@ -94,20 +111,129 @@ func (e Entry) IntDefault(def int) (int, error) { if v == nil { return def, errFindParse.Format("int", e.Key) } - if vint, ok := v.(int); ok { - return vint, nil - } else if vstring, sok := v.(string); sok && vstring != "" { - vint, err := strconv.Atoi(vstring) + + switch vv := v.(type) { + case string: + val, err := strconv.Atoi(vv) if err != nil { return def, err } - - return vint, nil + return val, nil + case int: + return vv, nil + case int8: + return int(vv), nil + case int16: + return int(vv), nil + case int32: + return int(vv), nil + case int64: + return int(vv), nil + case uint: + return int(vv), nil + case uint8: + return int(vv), nil + case uint16: + return int(vv), nil + case uint32: + return int(vv), nil + case uint64: + return int(vv), nil } return def, errFindParse.Format("int", e.Key) } +// Int8Default returns the entry's value as int8. +// If not found returns "def" and a non-nil error. +func (e Entry) Int8Default(def int8) (int8, error) { + v := e.ValueRaw + if v == nil { + return def, errFindParse.Format("int8", e.Key) + } + + switch vv := v.(type) { + case string: + val, err := strconv.ParseInt(vv, 10, 8) + if err != nil { + return def, err + } + return int8(val), nil + case int: + return int8(vv), nil + case int8: + return vv, nil + case int16: + return int8(vv), nil + case int32: + return int8(vv), nil + case int64: + return int8(vv), nil + } + + return def, errFindParse.Format("int8", e.Key) +} + +// Int16Default returns the entry's value as int16. +// If not found returns "def" and a non-nil error. +func (e Entry) Int16Default(def int16) (int16, error) { + v := e.ValueRaw + if v == nil { + return def, errFindParse.Format("int16", e.Key) + } + + switch vv := v.(type) { + case string: + val, err := strconv.ParseInt(vv, 10, 16) + if err != nil { + return def, err + } + return int16(val), nil + case int: + return int16(vv), nil + case int8: + return int16(vv), nil + case int16: + return vv, nil + case int32: + return int16(vv), nil + case int64: + return int16(vv), nil + } + + return def, errFindParse.Format("int16", e.Key) +} + +// Int32Default returns the entry's value as int32. +// If not found returns "def" and a non-nil error. +func (e Entry) Int32Default(def int32) (int32, error) { + v := e.ValueRaw + if v == nil { + return def, errFindParse.Format("int32", e.Key) + } + + switch vv := v.(type) { + case string: + val, err := strconv.ParseInt(vv, 10, 32) + if err != nil { + return def, err + } + return int32(val), nil + case int: + return int32(vv), nil + case int8: + return int32(vv), nil + case int16: + return int32(vv), nil + case int32: + return vv, nil + case int64: + return int32(vv), nil + } + + return def, errFindParse.Format("int32", e.Key) +} + // Int64Default returns the entry's value as int64. // If not found returns "def" and a non-nil error. func (e Entry) Int64Default(def int64) (int64, error) { @@ -116,85 +242,208 @@ func (e Entry) Int64Default(def int64) (int64, error) { return def, errFindParse.Format("int64", e.Key) } - if vint64, ok := v.(int64); ok { - return vint64, nil - } - - if vint, ok := v.(int); ok { - return int64(vint), nil - } - - if vstring, sok := v.(string); sok { - return strconv.ParseInt(vstring, 10, 64) + switch vv := v.(type) { + case string: + return strconv.ParseInt(vv, 10, 64) + case int64: + return vv, nil + case int32: + return int64(vv), nil + case int8: + return int64(vv), nil + case int: + return int64(vv), nil } return def, errFindParse.Format("int64", e.Key) } -// Float64Default returns the entry's value as float64. +// UintDefault returns the entry's value as uint. // If not found returns "def" and a non-nil error. -func (e Entry) Float64Default(def float64) (float64, error) { +func (e Entry) UintDefault(def uint) (uint, error) { v := e.ValueRaw - if v == nil { - return def, errFindParse.Format("float64", e.Key) + return def, errFindParse.Format("uint", e.Key) } - if vfloat32, ok := v.(float32); ok { - return float64(vfloat32), nil + x64 := strconv.IntSize == 64 + var maxValue uint = math.MaxUint32 + if x64 { + maxValue = math.MaxUint64 } - if vfloat64, ok := v.(float64); ok { - return vfloat64, nil - } - - if vint, ok := v.(int); ok { - return float64(vint), nil - } - - if vstring, sok := v.(string); sok { - vfloat64, err := strconv.ParseFloat(vstring, 64) + switch vv := v.(type) { + case string: + val, err := strconv.ParseUint(vv, 10, strconv.IntSize) if err != nil { return def, err } - - return vfloat64, nil + if val > uint64(maxValue) { + return def, errFindParse.Format("uint", e.Key) + } + return uint(val), nil + case uint: + return vv, nil + case uint8: + return uint(vv), nil + case uint16: + return uint(vv), nil + case uint32: + return uint(vv), nil + case uint64: + if vv > uint64(maxValue) { + return def, errFindParse.Format("uint", e.Key) + } + return uint(vv), nil + case int: + if vv < 0 || vv > int(maxValue) { + return def, errFindParse.Format("uint", e.Key) + } + return uint(vv), nil } - return def, errFindParse.Format("float64", e.Key) + return def, errFindParse.Format("uint", e.Key) } -// Float32Default returns the entry's value as float32. +// Uint8Default returns the entry's value as uint8. // If not found returns "def" and a non-nil error. -func (e Entry) Float32Default(key string, def float32) (float32, error) { +func (e Entry) Uint8Default(def uint8) (uint8, error) { v := e.ValueRaw - if v == nil { - return def, errFindParse.Format("float32", e.Key) + return def, errFindParse.Format("uint8", e.Key) } - if vfloat32, ok := v.(float32); ok { - return vfloat32, nil - } - - if vfloat64, ok := v.(float64); ok { - return float32(vfloat64), nil - } - - if vint, ok := v.(int); ok { - return float32(vint), nil - } - - if vstring, sok := v.(string); sok { - vfloat32, err := strconv.ParseFloat(vstring, 32) + switch vv := v.(type) { + case string: + val, err := strconv.ParseUint(vv, 10, 8) if err != nil { return def, err } - - return float32(vfloat32), nil + if val > math.MaxUint8 { + return def, errFindParse.Format("uint8", e.Key) + } + return uint8(val), nil + case uint: + if vv > math.MaxUint8 { + return def, errFindParse.Format("uint8", e.Key) + } + return uint8(vv), nil + case uint8: + return vv, nil + case uint16: + if vv > math.MaxUint8 { + return def, errFindParse.Format("uint8", e.Key) + } + return uint8(vv), nil + case uint32: + if vv > math.MaxUint8 { + return def, errFindParse.Format("uint8", e.Key) + } + return uint8(vv), nil + case uint64: + if vv > math.MaxUint8 { + return def, errFindParse.Format("uint8", e.Key) + } + return uint8(vv), nil + case int: + if vv < 0 || vv > math.MaxUint8 { + return def, errFindParse.Format("uint8", e.Key) + } + return uint8(vv), nil } - return def, errFindParse.Format("float32", e.Key) + return def, errFindParse.Format("uint8", e.Key) +} + +// Uint16Default returns the entry's value as uint16. +// If not found returns "def" and a non-nil error. +func (e Entry) Uint16Default(def uint16) (uint16, error) { + v := e.ValueRaw + if v == nil { + return def, errFindParse.Format("uint16", e.Key) + } + + switch vv := v.(type) { + case string: + val, err := strconv.ParseUint(vv, 10, 16) + if err != nil { + return def, err + } + if val > math.MaxUint16 { + return def, errFindParse.Format("uint16", e.Key) + } + return uint16(val), nil + case uint: + if vv > math.MaxUint16 { + return def, errFindParse.Format("uint16", e.Key) + } + return uint16(vv), nil + case uint8: + return uint16(vv), nil + case uint16: + return vv, nil + case uint32: + if vv > math.MaxUint16 { + return def, errFindParse.Format("uint16", e.Key) + } + return uint16(vv), nil + case uint64: + if vv > math.MaxUint16 { + return def, errFindParse.Format("uint16", e.Key) + } + return uint16(vv), nil + case int: + if vv < 0 || vv > math.MaxUint16 { + return def, errFindParse.Format("uint16", e.Key) + } + return uint16(vv), nil + } + + return def, errFindParse.Format("uint16", e.Key) +} + +// Uint32Default returns the entry's value as uint32. +// If not found returns "def" and a non-nil error. +func (e Entry) Uint32Default(def uint32) (uint32, error) { + v := e.ValueRaw + if v == nil { + return def, errFindParse.Format("uint32", e.Key) + } + + switch vv := v.(type) { + case string: + val, err := strconv.ParseUint(vv, 10, 32) + if err != nil { + return def, err + } + if val > math.MaxUint32 { + return def, errFindParse.Format("uint32", e.Key) + } + return uint32(val), nil + case uint: + if vv > math.MaxUint32 { + return def, errFindParse.Format("uint32", e.Key) + } + return uint32(vv), nil + case uint8: + return uint32(vv), nil + case uint16: + return uint32(vv), nil + case uint32: + return vv, nil + case uint64: + if vv > math.MaxUint32 { + return def, errFindParse.Format("uint32", e.Key) + } + return uint32(vv), nil + case int: + if vv < 0 || vv > math.MaxUint32 { + return def, errFindParse.Format("uint32", e.Key) + } + return uint32(vv), nil + } + + return def, errFindParse.Format("uint32", e.Key) } // Uint64Default returns the entry's value as uint64. @@ -205,25 +454,102 @@ func (e Entry) Uint64Default(def uint64) (uint64, error) { return def, errFindParse.Format("uint64", e.Key) } - if vuint64, ok := v.(uint64); ok { - return vuint64, nil - } - - if vint64, ok := v.(int64); ok { - return uint64(vint64), nil - } - - if vint, ok := v.(int); ok { - return uint64(vint), nil - } - - if vstring, sok := v.(string); sok { - return strconv.ParseUint(vstring, 10, 64) + switch vv := v.(type) { + case string: + val, err := strconv.ParseUint(vv, 10, 64) + if err != nil { + return def, err + } + if val > math.MaxUint64 { + return def, errFindParse.Format("uint64", e.Key) + } + return uint64(val), nil + case uint: + if vv > math.MaxUint64 { + return def, errFindParse.Format("uint64", e.Key) + } + return uint64(vv), nil + case uint8: + return uint64(vv), nil + case uint16: + return uint64(vv), nil + case uint32: + return uint64(vv), nil + case uint64: + return vv, nil + case int64: + return uint64(vv), nil + case int: + return uint64(vv), nil } return def, errFindParse.Format("uint64", e.Key) } +// Float32Default returns the entry's value as float32. +// If not found returns "def" and a non-nil error. +func (e Entry) Float32Default(key string, def float32) (float32, error) { + v := e.ValueRaw + if v == nil { + return def, errFindParse.Format("float32", e.Key) + } + + switch vv := v.(type) { + case string: + val, err := strconv.ParseFloat(vv, 32) + if err != nil { + return def, err + } + if val > math.MaxFloat32 { + return def, errFindParse.Format("float32", e.Key) + } + return float32(val), nil + case float32: + return vv, nil + case float64: + if vv > math.MaxFloat32 { + return def, errFindParse.Format("float32", e.Key) + } + return float32(vv), nil + case int: + return float32(vv), nil + } + + return def, errFindParse.Format("float32", e.Key) +} + +// Float64Default returns the entry's value as float64. +// If not found returns "def" and a non-nil error. +func (e Entry) Float64Default(def float64) (float64, error) { + v := e.ValueRaw + if v == nil { + return def, errFindParse.Format("float64", e.Key) + } + + switch vv := v.(type) { + case string: + val, err := strconv.ParseFloat(vv, 64) + if err != nil { + return def, err + } + return val, nil + case float32: + return float64(vv), nil + case float64: + return vv, nil + case int: + return float64(vv), nil + case int64: + return float64(vv), nil + case uint: + return float64(vv), nil + case uint64: + return float64(vv), nil + } + + return def, errFindParse.Format("float64", e.Key) +} + // BoolDefault returns the user's value as bool. // a string which is "1" or "t" or "T" or "TRUE" or "true" or "True" // or "0" or "f" or "F" or "FALSE" or "false" or "False". @@ -236,20 +562,17 @@ func (e Entry) BoolDefault(def bool) (bool, error) { return def, errFindParse.Format("bool", e.Key) } - if vBoolean, ok := v.(bool); ok { - return vBoolean, nil - } - - if vString, ok := v.(string); ok { - b, err := strconv.ParseBool(vString) + switch vv := v.(type) { + case string: + val, err := strconv.ParseBool(vv) if err != nil { return def, err } - return b, nil - } - - if vInt, ok := v.(int); ok { - if vInt == 1 { + return val, nil + case bool: + return vv, nil + case int: + if vv == 1 { return true, nil } return false, nil @@ -361,28 +684,39 @@ func (r *Store) SetImmutable(key string, value interface{}) (Entry, bool) { return r.Save(key, value, true) } +var emptyEntry Entry + // GetEntry returns a pointer to the "Entry" found with the given "key" -// if nothing found then it returns nil, so be careful with that, -// it's not supposed to be used by end-developers. -func (r *Store) GetEntry(key string) *Entry { +// if nothing found then it returns an empty Entry and false. +func (r *Store) GetEntry(key string) (Entry, bool) { args := *r n := len(args) for i := 0; i < n; i++ { - kv := &args[i] - if kv.Key == key { - return kv + if kv := args[i]; kv.Key == key { + return kv, true } } - return nil + return emptyEntry, false +} + +// GetEntryAt returns the internal Entry of the memstore based on its index, +// the stored index by the router. +// If not found then it returns a zero Entry and false. +func (r *Store) GetEntryAt(index int) (Entry, bool) { + args := *r + if len(args) > index { + return args[index], true + } + return emptyEntry, false } // GetDefault returns the entry's value based on its key. // If not found returns "def". // This function checks for immutability as well, the rest don't. func (r *Store) GetDefault(key string, def interface{}) interface{} { - v := r.GetEntry(key) - if v == nil || v.ValueRaw == nil { + v, ok := r.GetEntry(key) + if !ok || v.ValueRaw == nil { return def } vv := v.Value() @@ -411,8 +745,8 @@ func (r *Store) Visit(visitor func(key string, value interface{})) { // GetStringDefault returns the entry's value as string, based on its key. // If not found returns "def". func (r *Store) GetStringDefault(key string, def string) string { - v := r.GetEntry(key) - if v == nil { + v, ok := r.GetEntry(key) + if !ok { return def } @@ -432,8 +766,8 @@ func (r *Store) GetStringTrim(name string) string { // GetInt returns the entry's value as int, based on its key. // If not found returns -1 and a non-nil error. func (r *Store) GetInt(key string) (int, error) { - v := r.GetEntry(key) - if v == nil { + v, ok := r.GetEntry(key) + if !ok { return 0, errFindParse.Format("int", key) } return v.IntDefault(-1) @@ -449,20 +783,60 @@ func (r *Store) GetIntDefault(key string, def int) int { return def } -// GetUint64 returns the entry's value as uint64, based on its key. -// If not found returns 0 and a non-nil error. -func (r *Store) GetUint64(key string) (uint64, error) { - v := r.GetEntry(key) - if v == nil { - return 0, errFindParse.Format("uint64", key) +// GetInt8 returns the entry's value as int8, based on its key. +// If not found returns -1 and a non-nil error. +func (r *Store) GetInt8(key string) (int8, error) { + v, ok := r.GetEntry(key) + if !ok { + return -1, errFindParse.Format("int8", key) } - return v.Uint64Default(0) + return v.Int8Default(-1) } -// GetUint64Default returns the entry's value as uint64, based on its key. +// GetInt8Default returns the entry's value as int8, based on its key. // If not found returns "def". -func (r *Store) GetUint64Default(key string, def uint64) uint64 { - if v, err := r.GetUint64(key); err == nil { +func (r *Store) GetInt8Default(key string, def int8) int8 { + if v, err := r.GetInt8(key); err == nil { + return v + } + + return def +} + +// GetInt16 returns the entry's value as int16, based on its key. +// If not found returns -1 and a non-nil error. +func (r *Store) GetInt16(key string) (int16, error) { + v, ok := r.GetEntry(key) + if !ok { + return -1, errFindParse.Format("int16", key) + } + return v.Int16Default(-1) +} + +// GetInt16Default returns the entry's value as int16, based on its key. +// If not found returns "def". +func (r *Store) GetInt16Default(key string, def int16) int16 { + if v, err := r.GetInt16(key); err == nil { + return v + } + + return def +} + +// GetInt32 returns the entry's value as int32, based on its key. +// If not found returns -1 and a non-nil error. +func (r *Store) GetInt32(key string) (int32, error) { + v, ok := r.GetEntry(key) + if !ok { + return -1, errFindParse.Format("int32", key) + } + return v.Int32Default(-1) +} + +// GetInt32Default returns the entry's value as int32, based on its key. +// If not found returns "def". +func (r *Store) GetInt32Default(key string, def int32) int32 { + if v, err := r.GetInt32(key); err == nil { return v } @@ -472,8 +846,8 @@ func (r *Store) GetUint64Default(key string, def uint64) uint64 { // GetInt64 returns the entry's value as int64, based on its key. // If not found returns -1 and a non-nil error. func (r *Store) GetInt64(key string) (int64, error) { - v := r.GetEntry(key) - if v == nil { + v, ok := r.GetEntry(key) + if !ok { return -1, errFindParse.Format("int64", key) } return v.Int64Default(-1) @@ -489,11 +863,111 @@ func (r *Store) GetInt64Default(key string, def int64) int64 { return def } +// GetUint returns the entry's value as uint, based on its key. +// If not found returns 0 and a non-nil error. +func (r *Store) GetUint(key string) (uint, error) { + v, ok := r.GetEntry(key) + if !ok { + return 0, errFindParse.Format("uint", key) + } + return v.UintDefault(0) +} + +// GetUintDefault returns the entry's value as uint, based on its key. +// If not found returns "def". +func (r *Store) GetUintDefault(key string, def uint) uint { + if v, err := r.GetUint(key); err == nil { + return v + } + + return def +} + +// GetUint8 returns the entry's value as uint8, based on its key. +// If not found returns 0 and a non-nil error. +func (r *Store) GetUint8(key string) (uint8, error) { + v, ok := r.GetEntry(key) + if !ok { + return 0, errFindParse.Format("uint8", key) + } + return v.Uint8Default(0) +} + +// GetUint8Default returns the entry's value as uint8, based on its key. +// If not found returns "def". +func (r *Store) GetUint8Default(key string, def uint8) uint8 { + if v, err := r.GetUint8(key); err == nil { + return v + } + + return def +} + +// GetUint16 returns the entry's value as uint16, based on its key. +// If not found returns 0 and a non-nil error. +func (r *Store) GetUint16(key string) (uint16, error) { + v, ok := r.GetEntry(key) + if !ok { + return 0, errFindParse.Format("uint16", key) + } + return v.Uint16Default(0) +} + +// GetUint16Default returns the entry's value as uint16, based on its key. +// If not found returns "def". +func (r *Store) GetUint16Default(key string, def uint16) uint16 { + if v, err := r.GetUint16(key); err == nil { + return v + } + + return def +} + +// GetUint32 returns the entry's value as uint32, based on its key. +// If not found returns 0 and a non-nil error. +func (r *Store) GetUint32(key string) (uint32, error) { + v, ok := r.GetEntry(key) + if !ok { + return 0, errFindParse.Format("uint32", key) + } + return v.Uint32Default(0) +} + +// GetUint32Default returns the entry's value as uint32, based on its key. +// If not found returns "def". +func (r *Store) GetUint32Default(key string, def uint32) uint32 { + if v, err := r.GetUint32(key); err == nil { + return v + } + + return def +} + +// GetUint64 returns the entry's value as uint64, based on its key. +// If not found returns 0 and a non-nil error. +func (r *Store) GetUint64(key string) (uint64, error) { + v, ok := r.GetEntry(key) + if !ok { + return 0, errFindParse.Format("uint64", key) + } + return v.Uint64Default(0) +} + +// GetUint64Default returns the entry's value as uint64, based on its key. +// If not found returns "def". +func (r *Store) GetUint64Default(key string, def uint64) uint64 { + if v, err := r.GetUint64(key); err == nil { + return v + } + + return def +} + // GetFloat64 returns the entry's value as float64, based on its key. // If not found returns -1 and a non nil error. func (r *Store) GetFloat64(key string) (float64, error) { - v := r.GetEntry(key) - if v == nil { + v, ok := r.GetEntry(key) + if !ok { return -1, errFindParse.Format("float64", key) } return v.Float64Default(-1) @@ -516,8 +990,8 @@ func (r *Store) GetFloat64Default(key string, def float64) float64 { // // If not found returns false and a non-nil error. func (r *Store) GetBool(key string) (bool, error) { - v := r.GetEntry(key) - if v == nil { + v, ok := r.GetEntry(key) + if !ok { return false, errFindParse.Format("bool", key) } diff --git a/core/router/api_builder.go b/core/router/api_builder.go index 242fbadb..9aa9a338 100644 --- a/core/router/api_builder.go +++ b/core/router/api_builder.go @@ -9,20 +9,18 @@ import ( "github.com/kataras/iris/context" "github.com/kataras/iris/core/errors" - "github.com/kataras/iris/core/router/macro" + "github.com/kataras/iris/macro" ) -const ( - // MethodNone is a Virtual method - // to store the "offline" routes. - MethodNone = "NONE" -) +// MethodNone is a Virtual method +// to store the "offline" routes. +const MethodNone = "NONE" var ( // AllMethods contains the valid http methods: // "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", // "PATCH", "OPTIONS", "TRACE". - AllMethods = [...]string{ + AllMethods = []string{ "GET", "POST", "PUT", @@ -68,7 +66,7 @@ func (r *repository) getAll() []*Route { // and child routers. type APIBuilder struct { // the api builder global macros registry - macros *macro.Map + macros *macro.Macros // the api builder global handlers per status code registry (used for custom http errors) errorCodeHandlers *ErrorCodeHandlers // the api builder global routes repository @@ -116,7 +114,7 @@ var _ RoutesProvider = (*APIBuilder)(nil) // passed to the default request handl // which is responsible to build the API and the router handler. func NewAPIBuilder() *APIBuilder { api := &APIBuilder{ - macros: defaultMacros(), + macros: macro.Defaults, errorCodeHandlers: defaultErrorCodeHandlers(), reporter: errors.NewReporter(), relativePath: "/", @@ -246,7 +244,7 @@ func (api *APIBuilder) Handle(method string, relativePath string, handlers ...co ) for _, m := range methods { - route, err = NewRoute(m, subdomain, path, possibleMainHandlerName, routeHandlers, api.macros) + route, err = NewRoute(m, subdomain, path, possibleMainHandlerName, routeHandlers, *api.macros) if err != nil { // template path parser errors: api.reporter.Add("%v -> %s:%s:%s", err, method, subdomain, path) return nil // fail on first error. @@ -270,10 +268,10 @@ func (api *APIBuilder) Handle(method string, relativePath string, handlers ...co // otherwise use `Party` which can handle many paths with different handlers and middlewares. // // Usage: -// app.HandleMany("GET", "/user /user/{id:int} /user/me", genericUserHandler) +// app.HandleMany("GET", "/user /user/{id:uint64} /user/me", genericUserHandler) // At the other side, with `Handle` we've had to write: // app.Handle("GET", "/user", userHandler) -// app.Handle("GET", "/user/{id:int}", userByIDHandler) +// app.Handle("GET", "/user/{id:uint64}", userByIDHandler) // app.Handle("GET", "/user/me", userMeHandler) // // This method is used behind the scenes at the `Controller` function @@ -411,11 +409,11 @@ func (api *APIBuilder) WildcardSubdomain(middleware ...context.Handler) Party { return api.Subdomain(SubdomainWildcardIndicator, middleware...) } -// Macros returns the macro map which is responsible -// to register custom macro functions for all routes. +// Macros returns the macro collection that is responsible +// to register custom macros with their own parameter types and their macro functions for all routes. // // Learn more at: https://github.com/kataras/iris/tree/master/_examples/routing/dynamic-path -func (api *APIBuilder) Macros() *macro.Map { +func (api *APIBuilder) Macros() *macro.Macros { return api.macros } diff --git a/core/router/handler.go b/core/router/handler.go index 24ecfc5d..cc91819f 100644 --- a/core/router/handler.go +++ b/core/router/handler.go @@ -11,40 +11,30 @@ import ( "github.com/kataras/iris/context" "github.com/kataras/iris/core/errors" "github.com/kataras/iris/core/netutil" - "github.com/kataras/iris/core/router/node" ) // RequestHandler the middle man between acquiring a context and releasing it. // By-default is the router algorithm. type RequestHandler interface { - // HandleRequest is same as context.Handler but its usage is only about routing, - // separate the concept here. + // HandleRequest should handle the request based on the Context. HandleRequest(context.Context) - // Build should builds the handler, it's being called on router's BuildRouter. + // Build should builds the handler, it's being called on router's BuildRouter. Build(provider RoutesProvider) error // RouteExists reports whether a particular route exists. RouteExists(ctx context.Context, method, path string) bool } -type tree struct { - Method string - // subdomain is empty for default-hostname routes, - // ex: mysubdomain. - Subdomain string - Nodes *node.Nodes -} - type routerHandler struct { - trees []*tree + trees []*trie hosts bool // true if at least one route contains a Subdomain. } var _ RequestHandler = &routerHandler{} -func (h *routerHandler) getTree(method, subdomain string) *tree { +func (h *routerHandler) getTree(method, subdomain string) *trie { for i := range h.trees { t := h.trees[i] - if t.Method == method && t.Subdomain == subdomain { + if t.method == method && t.subdomain == subdomain { return t } } @@ -64,12 +54,14 @@ func (h *routerHandler) addRoute(r *Route) error { t := h.getTree(method, subdomain) if t == nil { - n := node.Nodes{} + n := newTrieNode() // first time we register a route to this method with this subdomain - t = &tree{Method: method, Subdomain: subdomain, Nodes: &n} + t = &trie{method: method, subdomain: subdomain, root: n} h.trees = append(h.trees, t) } - return t.Nodes.Add(routeName, path, handlers) + + t.insert(path, routeName, handlers) + return nil } // NewDefaultHandler returns the handler which is responsible @@ -189,11 +181,11 @@ func (h *routerHandler) HandleRequest(ctx context.Context) { for i := range h.trees { t := h.trees[i] - if method != t.Method { + if method != t.method { continue } - if h.hosts && t.Subdomain != "" { + if h.hosts && t.subdomain != "" { requestHost := ctx.Host() if netutil.IsLoopbackSubdomain(requestHost) { // this fixes a bug when listening on @@ -202,7 +194,7 @@ func (h *routerHandler) HandleRequest(ctx context.Context) { continue // it's not a subdomain, it's something like 127.0.0.1 probably } // it's a dynamic wildcard subdomain, we have just to check if ctx.subdomain is not empty - if t.Subdomain == SubdomainWildcardIndicator { + if t.subdomain == SubdomainWildcardIndicator { // mydomain.com -> invalid // localhost -> invalid // sub.mydomain.com -> valid @@ -220,14 +212,14 @@ func (h *routerHandler) HandleRequest(ctx context.Context) { continue } // continue to that, any subdomain is valid. - } else if !strings.HasPrefix(requestHost, t.Subdomain) { // t.Subdomain contains the dot. + } else if !strings.HasPrefix(requestHost, t.subdomain) { // t.subdomain contains the dot. continue } } - routeName, handlers := t.Nodes.Find(path, ctx.Params()) - if len(handlers) > 0 { - ctx.SetCurrentRouteName(routeName) - ctx.Do(handlers) + n := t.search(path, ctx.Params()) + if n != nil { + ctx.SetCurrentRouteName(n.RouteName) + ctx.Do(n.Handlers) // found return } @@ -238,15 +230,12 @@ func (h *routerHandler) HandleRequest(ctx context.Context) { if ctx.Application().ConfigurationReadOnly().GetFireMethodNotAllowed() { for i := range h.trees { t := h.trees[i] - // a bit slower than previous implementation but @kataras let me to apply this change - // because it's more reliable. - // // if `Configuration#FireMethodNotAllowed` is kept as defaulted(false) then this function will not // run, therefore performance kept as before. - if t.Nodes.Exists(path) { + if h.subdomainAndPathAndMethodExists(ctx, t, "", path) { // RCF rfc2616 https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // The response MUST include an Allow header containing a list of valid methods for the requested resource. - ctx.Header("Allow", t.Method) + ctx.Header("Allow", t.method) ctx.StatusCode(http.StatusMethodNotAllowed) return } @@ -256,55 +245,55 @@ func (h *routerHandler) HandleRequest(ctx context.Context) { ctx.StatusCode(http.StatusNotFound) } +func (h *routerHandler) subdomainAndPathAndMethodExists(ctx context.Context, t *trie, method, path string) bool { + if method != "" && method != t.method { + return false + } + + if h.hosts && t.subdomain != "" { + requestHost := ctx.Host() + if netutil.IsLoopbackSubdomain(requestHost) { + // this fixes a bug when listening on + // 127.0.0.1:8080 for example + // and have a wildcard subdomain and a route registered to root domain. + return false // it's not a subdomain, it's something like 127.0.0.1 probably + } + // it's a dynamic wildcard subdomain, we have just to check if ctx.subdomain is not empty + if t.subdomain == SubdomainWildcardIndicator { + // mydomain.com -> invalid + // localhost -> invalid + // sub.mydomain.com -> valid + // sub.localhost -> valid + serverHost := ctx.Application().ConfigurationReadOnly().GetVHost() + if serverHost == requestHost { + return false // it's not a subdomain, it's a full domain (with .com...) + } + + dotIdx := strings.IndexByte(requestHost, '.') + slashIdx := strings.IndexByte(requestHost, '/') + if dotIdx > 0 && (slashIdx == -1 || slashIdx > dotIdx) { + // if "." was found anywhere but not at the first path segment (host). + } else { + return false + } + // continue to that, any subdomain is valid. + } else if !strings.HasPrefix(requestHost, t.subdomain) { // t.subdomain contains the dot. + return false + } + } + + n := t.search(path, ctx.Params()) + return n != nil +} + // RouteExists reports whether a particular route exists // It will search from the current subdomain of context's host, if not inside the root domain. func (h *routerHandler) RouteExists(ctx context.Context, method, path string) bool { for i := range h.trees { t := h.trees[i] - if method != t.Method { - continue - } - - if h.hosts && t.Subdomain != "" { - requestHost := ctx.Host() - if netutil.IsLoopbackSubdomain(requestHost) { - // this fixes a bug when listening on - // 127.0.0.1:8080 for example - // and have a wildcard subdomain and a route registered to root domain. - continue // it's not a subdomain, it's something like 127.0.0.1 probably - } - // it's a dynamic wildcard subdomain, we have just to check if ctx.subdomain is not empty - if t.Subdomain == SubdomainWildcardIndicator { - // mydomain.com -> invalid - // localhost -> invalid - // sub.mydomain.com -> valid - // sub.localhost -> valid - serverHost := ctx.Application().ConfigurationReadOnly().GetVHost() - if serverHost == requestHost { - continue // it's not a subdomain, it's a full domain (with .com...) - } - - dotIdx := strings.IndexByte(requestHost, '.') - slashIdx := strings.IndexByte(requestHost, '/') - if dotIdx > 0 && (slashIdx == -1 || slashIdx > dotIdx) { - // if "." was found anywhere but not at the first path segment (host). - } else { - continue - } - // continue to that, any subdomain is valid. - } else if !strings.HasPrefix(requestHost, t.Subdomain) { // t.Subdomain contains the dot. - continue - } - } - - _, handlers := t.Nodes.Find(path, ctx.Params()) - if len(handlers) > 0 { - // found + if h.subdomainAndPathAndMethodExists(ctx, t, method, path) { return true } - - // not found or method not allowed. - break } return false diff --git a/core/router/macro.go b/core/router/macro.go deleted file mode 100644 index ba6969ba..00000000 --- a/core/router/macro.go +++ /dev/null @@ -1,253 +0,0 @@ -package router - -import ( - "net/http" - "strconv" - "strings" - - "github.com/kataras/iris/context" - "github.com/kataras/iris/core/errors" - "github.com/kataras/iris/core/router/macro" - "github.com/kataras/iris/core/router/macro/interpreter/ast" -) - -// defaultMacros returns a new macro map which -// contains the default router's named param types functions. -func defaultMacros() *macro.Map { - macros := macro.NewMap() - // registers the String and Int default macro funcs - // user can add or override of his own funcs later on - // i.e: - // app.Macro.String.RegisterFunc("equal", func(eqWith string) func(string) bool { - // return func(paramValue string) bool { - // return eqWith == paramValue - // }}) - registerBuiltinsMacroFuncs(macros) - - return macros -} - -func registerBuiltinsMacroFuncs(out *macro.Map) { - // register the String which is the default type if not - // parameter type is specified or - // if a given parameter into path given but the func doesn't exist on the - // parameter type's function list. - // - // these can be overridden by the user, later on. - registerStringMacroFuncs(out.String) - registerIntMacroFuncs(out.Int) - registerIntMacroFuncs(out.Long) - registerAlphabeticalMacroFuncs(out.Alphabetical) - registerFileMacroFuncs(out.File) - registerPathMacroFuncs(out.Path) -} - -// String -// anything one part -func registerStringMacroFuncs(out *macro.Macro) { - // this can be used everywhere, it's to help users to define custom regexp expressions - // on all macros - out.RegisterFunc("regexp", func(expr string) macro.EvaluatorFunc { - regexpEvaluator := macro.MustNewEvaluatorFromRegexp(expr) - return regexpEvaluator - }) - - // checks if param value starts with the 'prefix' arg - out.RegisterFunc("prefix", func(prefix string) macro.EvaluatorFunc { - return func(paramValue string) bool { - return strings.HasPrefix(paramValue, prefix) - } - }) - - // checks if param value ends with the 'suffix' arg - out.RegisterFunc("suffix", func(suffix string) macro.EvaluatorFunc { - return func(paramValue string) bool { - return strings.HasSuffix(paramValue, suffix) - } - }) - - // checks if param value contains the 's' arg - out.RegisterFunc("contains", func(s string) macro.EvaluatorFunc { - return func(paramValue string) bool { - return strings.Contains(paramValue, s) - } - }) - - // checks if param value's length is at least 'min' - out.RegisterFunc("min", func(min int) macro.EvaluatorFunc { - return func(paramValue string) bool { - return len(paramValue) >= min - } - }) - // checks if param value's length is not bigger than 'max' - out.RegisterFunc("max", func(max int) macro.EvaluatorFunc { - return func(paramValue string) bool { - return max >= len(paramValue) - } - }) -} - -// Int -// only numbers (0-9) -func registerIntMacroFuncs(out *macro.Macro) { - // checks if the param value's int representation is - // bigger or equal than 'min' - out.RegisterFunc("min", func(min int) macro.EvaluatorFunc { - return func(paramValue string) bool { - n, err := strconv.Atoi(paramValue) - if err != nil { - return false - } - return n >= min - } - }) - - // checks if the param value's int representation is - // smaller or equal than 'max' - out.RegisterFunc("max", func(max int) macro.EvaluatorFunc { - return func(paramValue string) bool { - n, err := strconv.Atoi(paramValue) - if err != nil { - return false - } - return n <= max - } - }) - - // checks if the param value's int representation is - // between min and max, including 'min' and 'max' - out.RegisterFunc("range", func(min, max int) macro.EvaluatorFunc { - return func(paramValue string) bool { - n, err := strconv.Atoi(paramValue) - if err != nil { - return false - } - - if n < min || n > max { - return false - } - return true - } - }) -} - -// Alphabetical -// letters only (upper or lowercase) -func registerAlphabeticalMacroFuncs(out *macro.Macro) { - -} - -// File -// letters (upper or lowercase) -// numbers (0-9) -// underscore (_) -// dash (-) -// point (.) -// no spaces! or other character -func registerFileMacroFuncs(out *macro.Macro) { - -} - -// Path -// File+slashes(anywhere) -// should be the latest param, it's the wildcard -func registerPathMacroFuncs(out *macro.Macro) { - -} - -// compileRoutePathAndHandlers receives a route info and returns its parsed/"compiled" path -// and the new handlers (prepend all the macro's handler, if any). -// -// It's not exported for direct use. -func compileRoutePathAndHandlers(handlers context.Handlers, tmpl *macro.Template) (string, context.Handlers, error) { - // parse the path to node's path, now. - path, err := convertTmplToNodePath(tmpl) - if err != nil { - return tmpl.Src, handlers, err - } - // prepend the macro handler to the route, now, - // right before the register to the tree, so routerbuilder.UseGlobal will work as expected. - if len(tmpl.Params) > 0 { - macroEvaluatorHandler := convertTmplToHandler(tmpl) - // may return nil if no really need a macro handler evaluator - if macroEvaluatorHandler != nil { - handlers = append(context.Handlers{macroEvaluatorHandler}, handlers...) - } - } - - return path, handlers, nil -} - -func convertTmplToNodePath(tmpl *macro.Template) (string, error) { - routePath := tmpl.Src - if len(tmpl.Params) > 0 { - if routePath[len(routePath)-1] == '/' { - routePath = routePath[0 : len(routePath)-2] // remove the last "/" if macro syntax instead of underline's - } - } - - // if it has started with {} and it's valid - // then the tmpl.Params will be filled, - // so no any further check needed - for i, p := range tmpl.Params { - if p.Type == ast.ParamTypePath { - if i != len(tmpl.Params)-1 { - return "", errors.New("parameter type \"ParamTypePath\" should be putted to the very last of a path") - } - routePath = strings.Replace(routePath, p.Src, WildcardParam(p.Name), 1) - } else { - routePath = strings.Replace(routePath, p.Src, Param(p.Name), 1) - } - } - - return routePath, nil -} - -// note: returns nil if not needed, the caller(router) should be check for that before adding that on route's Middleware -func convertTmplToHandler(tmpl *macro.Template) context.Handler { - - needMacroHandler := false - - // check if we have params like: {name:string} or {name} or {anything:path} without else keyword or any functions used inside these params. - // 1. if we don't have, then we don't need to add a handler before the main route's handler (as I said, no performance if macro is not really used) - // 2. if we don't have any named params then we don't need a handler too. - for _, p := range tmpl.Params { - if len(p.Funcs) == 0 && (p.Type == ast.ParamTypeUnExpected || p.Type == ast.ParamTypeString || p.Type == ast.ParamTypePath) && p.ErrCode == http.StatusNotFound { - } else { - // println("we need handler for: " + tmpl.Src) - needMacroHandler = true - } - } - - if !needMacroHandler { - // println("we don't need handler for: " + tmpl.Src) - return nil - } - - return func(tmpl macro.Template) context.Handler { - return func(ctx context.Context) { - for _, p := range tmpl.Params { - paramValue := ctx.Params().Get(p.Name) - // first, check for type evaluator - if !p.TypeEvaluator(paramValue) { - ctx.StatusCode(p.ErrCode) - ctx.StopExecution() - return - } - - // then check for all of its functions - for _, evalFunc := range p.Funcs { - if !evalFunc(paramValue) { - ctx.StatusCode(p.ErrCode) - ctx.StopExecution() - return - } - } - - } - // if all passed, just continue - ctx.Next() - } - }(*tmpl) - -} diff --git a/core/router/macro/interpreter/ast/ast.go b/core/router/macro/interpreter/ast/ast.go deleted file mode 100644 index 23e17236..00000000 --- a/core/router/macro/interpreter/ast/ast.go +++ /dev/null @@ -1,215 +0,0 @@ -package ast - -import ( - "fmt" - "reflect" - "strconv" -) - -// ParamType is a specific uint8 type -// which holds the parameter types' type. -type ParamType uint8 - -const ( - // ParamTypeUnExpected is an unexpected parameter type. - ParamTypeUnExpected ParamType = iota - // ParamTypeString is the string type. - // If parameter type is missing then it defaults to String type. - // Allows anything - // Declaration: /mypath/{myparam:string} or /mypath{myparam} - ParamTypeString - // ParamTypeInt is the integer, a number type. - // Allows only positive numbers (0-9) - // Declaration: /mypath/{myparam:int} - ParamTypeInt - // ParamTypeLong is the integer, a number type. - // Allows only positive numbers (0-9) - // Declaration: /mypath/{myparam:long} - ParamTypeLong - // ParamTypeBoolean is the bool type. - // Allows only "1" or "t" or "T" or "TRUE" or "true" or "True" - // or "0" or "f" or "F" or "FALSE" or "false" or "False". - // Declaration: /mypath/{myparam:boolean} - ParamTypeBoolean - // ParamTypeAlphabetical is the alphabetical/letter type type. - // Allows letters only (upper or lowercase) - // Declaration: /mypath/{myparam:alphabetical} - ParamTypeAlphabetical - // ParamTypeFile is the file single path type. - // Allows: - // letters (upper or lowercase) - // numbers (0-9) - // underscore (_) - // dash (-) - // point (.) - // no spaces! or other character - // Declaration: /mypath/{myparam:file} - ParamTypeFile - // ParamTypePath is the multi path (or wildcard) type. - // Allows anything, should be the last part - // Declaration: /mypath/{myparam:path} - ParamTypePath -) - -func (pt ParamType) String() string { - for k, v := range paramTypes { - if v == pt { - return k - } - } - - return "unexpected" -} - -// Not because for a single reason -// a string may be a -// ParamTypeString or a ParamTypeFile -// or a ParamTypePath or ParamTypeAlphabetical. -// -// func ParamTypeFromStd(k reflect.Kind) ParamType { - -// Kind returns the std kind of this param type. -func (pt ParamType) Kind() reflect.Kind { - switch pt { - case ParamTypeAlphabetical: - fallthrough - case ParamTypeFile: - fallthrough - case ParamTypePath: - fallthrough - case ParamTypeString: - return reflect.String - case ParamTypeInt: - return reflect.Int - case ParamTypeLong: - return reflect.Int64 - case ParamTypeBoolean: - return reflect.Bool - } - return reflect.Invalid // 0 -} - -// ValidKind will return true if at least one param type is supported -// for this std kind. -func ValidKind(k reflect.Kind) bool { - switch k { - case reflect.String: - fallthrough - case reflect.Int: - fallthrough - case reflect.Int64: - fallthrough - case reflect.Bool: - return true - default: - return false - } -} - -// Assignable returns true if the "k" standard type -// is assignabled to this ParamType. -func (pt ParamType) Assignable(k reflect.Kind) bool { - return pt.Kind() == k -} - -var paramTypes = map[string]ParamType{ - "string": ParamTypeString, - "int": ParamTypeInt, - "long": ParamTypeLong, - "boolean": ParamTypeBoolean, - "alphabetical": ParamTypeAlphabetical, - "file": ParamTypeFile, - "path": ParamTypePath, - // could be named also: - // "tail": - // "wild" - // "wildcard" - -} - -// LookupParamType accepts the string -// representation of a parameter type. -// Available: -// "string" -// "int" -// "long" -// "alphabetical" -// "file" -// "path" -func LookupParamType(ident string) ParamType { - if typ, ok := paramTypes[ident]; ok { - return typ - } - return ParamTypeUnExpected -} - -// LookupParamTypeFromStd accepts the string representation of a standard go type. -// It returns a ParamType, but it may differs for example -// the alphabetical, file, path and string are all string go types, so -// make sure that caller resolves these types before this call. -// -// string matches to string -// int matches to int -// int64 matches to long -// bool matches to boolean -func LookupParamTypeFromStd(goType string) ParamType { - switch goType { - case "string": - return ParamTypeString - case "int": - return ParamTypeInt - case "int64": - return ParamTypeLong - case "bool": - return ParamTypeBoolean - default: - return ParamTypeUnExpected - } -} - -// ParamStatement is a struct -// which holds all the necessary information about a macro parameter. -// It holds its type (string, int, alphabetical, file, path), -// its source ({param:type}), -// its name ("param"), -// its attached functions by the user (min, max...) -// and the http error code if that parameter -// failed to be evaluated. -type ParamStatement struct { - Src string // the original unparsed source, i.e: {id:int range(1,5) else 404} - Name string // id - Type ParamType // int - Funcs []ParamFunc // range - ErrorCode int // 404 -} - -// ParamFuncArg represents a single parameter function's argument -type ParamFuncArg interface{} - -// ParamFuncArgToInt converts and returns -// any type of "a", to an integer. -func ParamFuncArgToInt(a ParamFuncArg) (int, error) { - switch a.(type) { - case int: - return a.(int), nil - case string: - return strconv.Atoi(a.(string)) - case int64: - return int(a.(int64)), nil - default: - return -1, fmt.Errorf("unexpected function argument type: %q", a) - } -} - -// ParamFunc holds the name of a parameter's function -// and its arguments (values) -// A param func is declared with: -// {param:int range(1,5)}, -// the range is the -// param function name -// the 1 and 5 are the two param function arguments -// range(1,5) -type ParamFunc struct { - Name string // range - Args []ParamFuncArg // [1,5] -} diff --git a/core/router/macro/macro.go b/core/router/macro/macro.go deleted file mode 100644 index e4141c07..00000000 --- a/core/router/macro/macro.go +++ /dev/null @@ -1,292 +0,0 @@ -package macro - -import ( - "fmt" - "reflect" - "regexp" - "strconv" - "unicode" - - "github.com/kataras/iris/core/router/macro/interpreter/ast" -) - -// EvaluatorFunc is the signature for both param types and param funcs. -// It should accepts the param's value as string -// and return true if validated otherwise false. -type EvaluatorFunc func(paramValue string) bool - -// NewEvaluatorFromRegexp accepts a regexp "expr" expression -// and returns an EvaluatorFunc based on that regexp. -// the regexp is compiled before return. -// -// Returns a not-nil error on regexp compile failure. -func NewEvaluatorFromRegexp(expr string) (EvaluatorFunc, error) { - if expr == "" { - return nil, fmt.Errorf("empty regex expression") - } - - // add the last $ if missing (and not wildcard(?)) - if i := expr[len(expr)-1]; i != '$' && i != '*' { - expr += "$" - } - - r, err := regexp.Compile(expr) - if err != nil { - return nil, err - } - - return r.MatchString, nil -} - -// MustNewEvaluatorFromRegexp same as NewEvaluatorFromRegexp -// but it panics on the "expr" parse failure. -func MustNewEvaluatorFromRegexp(expr string) EvaluatorFunc { - r, err := NewEvaluatorFromRegexp(expr) - if err != nil { - panic(err) - } - return r -} - -var ( - goodParamFuncReturnType = reflect.TypeOf(func(string) bool { return false }) - goodParamFuncReturnType2 = reflect.TypeOf(EvaluatorFunc(func(string) bool { return false })) -) - -func goodParamFunc(typ reflect.Type) bool { - // should be a func - // which returns a func(string) bool - if typ.Kind() == reflect.Func { - if typ.NumOut() == 1 { - typOut := typ.Out(0) - if typOut == goodParamFuncReturnType || typOut == goodParamFuncReturnType2 { - return true - } - } - } - - return false -} - -// goodParamFuncName reports whether the function name is a valid identifier. -func goodParamFuncName(name string) bool { - if name == "" { - return false - } - // valid names are only letters and _ - for _, r := range name { - switch { - case r == '_': - case !unicode.IsLetter(r): - return false - } - } - return true -} - -// the convertBuilderFunc return value is generating at boot time. -// convertFunc converts an interface to a valid full param function. -func convertBuilderFunc(fn interface{}) ParamEvaluatorBuilder { - - typFn := reflect.TypeOf(fn) - if !goodParamFunc(typFn) { - return nil - } - - numFields := typFn.NumIn() - - return func(args []ast.ParamFuncArg) EvaluatorFunc { - if len(args) != numFields { - // no variadics support, for now. - panic("args should be the same len as numFields") - } - var argValues []reflect.Value - for i := 0; i < numFields; i++ { - field := typFn.In(i) - arg := args[i] - - if field.Kind() != reflect.TypeOf(arg).Kind() { - panic("fields should have the same type") - } - - argValues = append(argValues, reflect.ValueOf(arg)) - } - - evalFn := reflect.ValueOf(fn).Call(argValues)[0].Interface() - - var evaluator EvaluatorFunc - // check for typed and not typed - if _v, ok := evalFn.(EvaluatorFunc); ok { - evaluator = _v - } else if _v, ok = evalFn.(func(string) bool); ok { - evaluator = _v - } - return func(paramValue string) bool { - return evaluator(paramValue) - } - } -} - -type ( - // Macro represents the parsed macro, - // which holds - // the evaluator (param type's evaluator + param functions evaluators) - // and its param functions. - // - // Any type contains its own macro - // instance, so an String type - // contains its type evaluator - // which is the "Evaluator" field - // and it can register param functions - // to that macro which maps to a parameter type. - Macro struct { - Evaluator EvaluatorFunc - funcs []ParamFunc - } - - // ParamEvaluatorBuilder is a func - // which accepts a param function's arguments (values) - // and returns an EvaluatorFunc, its job - // is to make the macros to be registered - // by user at the most generic possible way. - ParamEvaluatorBuilder func([]ast.ParamFuncArg) EvaluatorFunc - - // ParamFunc represents the parsed - // parameter function, it holds - // the parameter's name - // and the function which will build - // the evaluator func. - ParamFunc struct { - Name string - Func ParamEvaluatorBuilder - } -) - -func newMacro(evaluator EvaluatorFunc) *Macro { - return &Macro{Evaluator: evaluator} -} - -// RegisterFunc registers a parameter function -// to that macro. -// Accepts the func name ("range") -// and the function body, which should return an EvaluatorFunc -// a bool (it will be converted to EvaluatorFunc later on), -// i.e RegisterFunc("min", func(minValue int) func(paramValue string) bool){}) -func (m *Macro) RegisterFunc(funcName string, fn interface{}) { - fullFn := convertBuilderFunc(fn) - m.registerFunc(funcName, fullFn) -} - -func (m *Macro) registerFunc(funcName string, fullFn ParamEvaluatorBuilder) { - if !goodParamFuncName(funcName) { - return - } - - for _, fn := range m.funcs { - if fn.Name == funcName { - fn.Func = fullFn - return - } - } - - m.funcs = append(m.funcs, ParamFunc{ - Name: funcName, - Func: fullFn, - }) -} - -func (m *Macro) getFunc(funcName string) ParamEvaluatorBuilder { - for _, fn := range m.funcs { - if fn.Name == funcName { - if fn.Func == nil { - continue - } - return fn.Func - } - } - return nil -} - -// Map contains the default macros mapped to their types. -// This is the manager which is used by the caller to register custom -// parameter functions per param-type (String, Int, Long, Boolean, Alphabetical, File, Path). -type Map struct { - // string type - // anything - String *Macro - // uint type - // only positive numbers (+0-9) - // it could be uint/uint32 but we keep int for simplicity - Int *Macro - // long an int64 type - // only positive numbers (+0-9) - // it could be uint64 but we keep int64 for simplicity - Long *Macro - // boolean as bool type - // a string which is "1" or "t" or "T" or "TRUE" or "true" or "True" - // or "0" or "f" or "F" or "FALSE" or "false" or "False". - Boolean *Macro - // alphabetical/letter type - // letters only (upper or lowercase) - Alphabetical *Macro - // file type - // letters (upper or lowercase) - // numbers (0-9) - // underscore (_) - // dash (-) - // point (.) - // no spaces! or other character - File *Macro - // path type - // anything, should be the last part - Path *Macro -} - -// NewMap returns a new macro Map with default -// type evaluators. -// -// Learn more at: https://github.com/kataras/iris/tree/master/_examples/routing/dynamic-path -func NewMap() *Map { - return &Map{ - // it allows everything, so no need for a regexp here. - String: newMacro(func(string) bool { return true }), - Int: newMacro(MustNewEvaluatorFromRegexp("^[0-9]+$")), - Long: newMacro(MustNewEvaluatorFromRegexp("^[0-9]+$")), - Boolean: newMacro(func(paramValue string) bool { - // a simple if statement is faster than regex ^(true|false|True|False|t|0|f|FALSE|TRUE)$ - // in this case. - _, err := strconv.ParseBool(paramValue) - return err == nil - }), - Alphabetical: newMacro(MustNewEvaluatorFromRegexp("^[a-zA-Z ]+$")), - File: newMacro(MustNewEvaluatorFromRegexp("^[a-zA-Z0-9_.-]*$")), - // it allows everything, we have String and Path as different - // types because I want to give the opportunity to the user - // to organise the macro functions based on wildcard or single dynamic named path parameter. - // Should be the last. - Path: newMacro(func(string) bool { return true }), - } -} - -// Lookup returns the specific Macro from the map -// based on the parameter type. -// i.e if ast.ParamTypeInt then it will return the m.Int. -// Returns the m.String if not matched. -func (m *Map) Lookup(typ ast.ParamType) *Macro { - switch typ { - case ast.ParamTypeInt: - return m.Int - case ast.ParamTypeLong: - return m.Long - case ast.ParamTypeBoolean: - return m.Boolean - case ast.ParamTypeAlphabetical: - return m.Alphabetical - case ast.ParamTypeFile: - return m.File - case ast.ParamTypePath: - return m.Path - default: - return m.String - } -} diff --git a/core/router/macro/macro_test.go b/core/router/macro/macro_test.go deleted file mode 100644 index d412da29..00000000 --- a/core/router/macro/macro_test.go +++ /dev/null @@ -1,186 +0,0 @@ -package macro - -import ( - "reflect" - "testing" -) - -// Most important tests to look: -// ../parser/parser_test.go -// ../lexer/lexer_test.go - -func TestGoodParamFunc(t *testing.T) { - good1 := func(min int, max int) func(string) bool { - return func(paramValue string) bool { - return true - } - } - - good2 := func(min int, max int) func(string) bool { - return func(paramValue string) bool { - return true - } - } - - notgood1 := func(min int, max int) bool { - return false - } - - if !goodParamFunc(reflect.TypeOf(good1)) { - t.Fatalf("expected good1 func to be good but it's not") - } - - if !goodParamFunc(reflect.TypeOf(good2)) { - t.Fatalf("expected good2 func to be good but it's not") - } - - if goodParamFunc(reflect.TypeOf(notgood1)) { - t.Fatalf("expected notgood1 func to be the worst") - } -} - -func TestGoodParamFuncName(t *testing.T) { - tests := []struct { - name string - good bool - }{ - {"range", true}, - {"_range", true}, - {"range_", true}, - {"r_ange", true}, - // numbers or other symbols are invalid. - {"range1", false}, - {"2range", false}, - {"r@nge", false}, - {"rang3", false}, - } - for i, tt := range tests { - isGood := goodParamFuncName(tt.name) - if tt.good && !isGood { - t.Fatalf("tests[%d] - expecting valid name but got invalid for name %s", i, tt.name) - } else if !tt.good && isGood { - t.Fatalf("tests[%d] - expecting invalid name but got valid for name %s", i, tt.name) - } - } -} - -func testEvaluatorRaw(macroEvaluator *Macro, input string, pass bool, i int, t *testing.T) { - if got := macroEvaluator.Evaluator(input); pass != got { - t.Fatalf("tests[%d] - expecting %v but got %v", i, pass, got) - } -} - -func TestStringEvaluatorRaw(t *testing.T) { - f := NewMap() - - tests := []struct { - pass bool - input string - }{ - {true, "astring"}, // 0 - {true, "astringwith_numb3rS_and_symbol$"}, // 1 - {true, "32321"}, // 2 - {true, "main.css"}, // 3 - {true, "/assets/main.css"}, // 4 - // false never - } // 0 - - for i, tt := range tests { - testEvaluatorRaw(f.String, tt.input, tt.pass, i, t) - } -} - -func TestIntEvaluatorRaw(t *testing.T) { - f := NewMap() - - tests := []struct { - pass bool - input string - }{ - {false, "astring"}, // 0 - {false, "astringwith_numb3rS_and_symbol$"}, // 1 - {true, "32321"}, // 2 - {false, "main.css"}, // 3 - {false, "/assets/main.css"}, // 4 - } - - for i, tt := range tests { - testEvaluatorRaw(f.Int, tt.input, tt.pass, i, t) - } -} - -func TestAlphabeticalEvaluatorRaw(t *testing.T) { - f := NewMap() - - tests := []struct { - pass bool - input string - }{ - {true, "astring"}, // 0 - {false, "astringwith_numb3rS_and_symbol$"}, // 1 - {false, "32321"}, // 2 - {false, "main.css"}, // 3 - {false, "/assets/main.css"}, // 4 - } - - for i, tt := range tests { - testEvaluatorRaw(f.Alphabetical, tt.input, tt.pass, i, t) - } -} - -func TestFileEvaluatorRaw(t *testing.T) { - f := NewMap() - - tests := []struct { - pass bool - input string - }{ - {true, "astring"}, // 0 - {false, "astringwith_numb3rS_and_symbol$"}, // 1 - {true, "32321"}, // 2 - {true, "main.css"}, // 3 - {false, "/assets/main.css"}, // 4 - } - - for i, tt := range tests { - testEvaluatorRaw(f.File, tt.input, tt.pass, i, t) - } -} - -func TestPathEvaluatorRaw(t *testing.T) { - f := NewMap() - - pathTests := []struct { - pass bool - input string - }{ - {true, "astring"}, // 0 - {true, "astringwith_numb3rS_and_symbol$"}, // 1 - {true, "32321"}, // 2 - {true, "main.css"}, // 3 - {true, "/assets/main.css"}, // 4 - {true, "disk/assets/main.css"}, // 5 - } - - for i, tt := range pathTests { - testEvaluatorRaw(f.Path, tt.input, tt.pass, i, t) - } -} - -// func TestMapRegisterFunc(t *testing.T) { -// m := NewMap() -// m.String.RegisterFunc("prefix", func(prefix string) EvaluatorFunc { -// return func(paramValue string) bool { -// return strings.HasPrefix(paramValue, prefix) -// } -// }) - -// p, err := Parse("/user/@iris") -// if err != nil { -// t.Fatalf(err) -// } - -// // p.Params = append(p.) - -// testEvaluatorRaw(m.String, p.Src, false, 0, t) -// } diff --git a/core/router/macro/template.go b/core/router/macro/template.go deleted file mode 100644 index f26c1d06..00000000 --- a/core/router/macro/template.go +++ /dev/null @@ -1,75 +0,0 @@ -package macro - -import ( - "github.com/kataras/iris/core/router/macro/interpreter/ast" - "github.com/kataras/iris/core/router/macro/interpreter/parser" -) - -// Template contains a route's path full parsed template. -// -// Fields: -// Src is the raw source of the path, i.e /users/{id:int min(1)} -// Params is the list of the Params that are being used to the -// path, i.e the min as param name and 1 as the param argument. -type Template struct { - // Src is the original template given by the client - Src string `json:"src"` - Params []TemplateParam `json:"params"` -} - -// TemplateParam is the parsed macro parameter's template -// they are being used to describe the param's syntax result. -type TemplateParam struct { - Src string `json:"src"` // the unparsed param'false source - // Type is not useful anywhere here but maybe - // it's useful on host to decide how to convert the path template to specific router's syntax - Type ast.ParamType `json:"type"` - Name string `json:"name"` - ErrCode int `json:"errCode"` - TypeEvaluator EvaluatorFunc `json:"-"` - Funcs []EvaluatorFunc `json:"-"` -} - -// Parse takes a full route path and a macro map (macro map contains the macro types with their registered param functions) -// and returns a new Template. -// It builds all the parameter functions for that template -// and their evaluators, it's the api call that makes use the interpeter's parser -> lexer. -func Parse(src string, macros *Map) (*Template, error) { - params, err := parser.Parse(src) - if err != nil { - return nil, err - } - t := new(Template) - t.Src = src - - for _, p := range params { - funcMap := macros.Lookup(p.Type) - typEval := funcMap.Evaluator - - tmplParam := TemplateParam{ - Src: p.Src, - Type: p.Type, - Name: p.Name, - ErrCode: p.ErrorCode, - TypeEvaluator: typEval, - } - for _, paramfn := range p.Funcs { - tmplFn := funcMap.getFunc(paramfn.Name) - if tmplFn == nil { // if not find on this type, check for String's which is for global funcs too - tmplFn = macros.String.getFunc(paramfn.Name) - if tmplFn == nil { // if not found then just skip this param - continue - } - } - evalFn := tmplFn(paramfn.Args) - if evalFn == nil { - continue - } - tmplParam.Funcs = append(tmplParam.Funcs, evalFn) - } - - t.Params = append(t.Params, tmplParam) - } - - return t, nil -} diff --git a/core/router/node/node.go b/core/router/node/node.go deleted file mode 100644 index 4a4adb05..00000000 --- a/core/router/node/node.go +++ /dev/null @@ -1,448 +0,0 @@ -package node - -import ( - "sort" - "strings" - - "github.com/kataras/iris/context" - "github.com/kataras/iris/core/errors" -) - -// Nodes a conversion type for []*node. -type Nodes []*node - -type node struct { - s string - routeName string - wildcardParamName string // name of the wildcard parameter, only one per whole Node is allowed - paramNames []string // only-names - childrenNodes Nodes - handlers context.Handlers - root bool - rootWildcard bool // if it's a wildcard {path} type on root, it should allow everything but it is not conflicts with - // any other static or dynamic or wildcard paths if exists on other nodes. -} - -// ErrDublicate returnned from `Add` when two or more routes have the same registered path. -var ErrDublicate = errors.New("two or more routes have the same registered path") - -/// TODO: clean up needed until v8.5 - -// Add adds a node to the tree, returns an ErrDublicate error on failure. -func (nodes *Nodes) Add(routeName string, path string, handlers context.Handlers) error { - // println("[Add] adding path: " + path) - // resolve params and if that node should be added as root - var params []string - var paramStart, paramEnd int - for { - paramStart = strings.IndexByte(path[paramEnd:], ':') - if paramStart == -1 { - break - } - paramStart += paramEnd - paramStart++ - paramEnd = strings.IndexByte(path[paramStart:], '/') - - if paramEnd == -1 { - params = append(params, path[paramStart:]) - path = path[:paramStart] - break - } - paramEnd += paramStart - params = append(params, path[paramStart:paramEnd]) - path = path[:paramStart] + path[paramEnd:] - paramEnd -= paramEnd - paramStart - } - - var p []int - for i := 0; i < len(path); i++ { - idx := strings.IndexByte(path[i:], ':') - if idx == -1 { - break - } - p = append(p, idx+i) - i = idx + i - } - - for _, idx := range p { - // print("-2 nodes.Add: path: " + path + " params len: ") - // println(len(params)) - if err := nodes.add(routeName, path[:idx], nil, nil, true); err != nil { - return err - } - // print("-1 nodes.Add: path: " + path + " params len: ") - // println(len(params)) - if nidx := idx + 1; len(path) > nidx { - if err := nodes.add(routeName, path[:nidx], nil, nil, true); err != nil { - return err - } - } - } - - // print("nodes.Add: path: " + path + " params len: ") - // println(len(params)) - if err := nodes.add(routeName, path, params, handlers, true); err != nil { - return err - } - - // prioritize by static path remember, they were already sorted by subdomains too. - nodes.prioritize() - return nil -} - -func (nodes *Nodes) add(routeName, path string, paramNames []string, handlers context.Handlers, root bool) (err error) { - // println("[add] route name: " + routeName) - // println("[add] adding path: " + path) - - // wraia etsi doulevei ara - // na to kanw na exei to node to diko tou wildcard parameter name - // kai sto telos na pernei auto, me vasi to *paramname - // alla edw mesa 9a ginete register vasi tou last / - - // set the wildcard param name to the root and its children. - wildcardIdx := strings.IndexByte(path, '*') - wildcardParamName := "" - if wildcardIdx > 0 && len(paramNames) == 0 { // 27 Oct comment: && len(paramNames) == 0 { - wildcardParamName = path[wildcardIdx+1:] - path = path[0:wildcardIdx-1] + "/" // replace *paramName with single slash - - // if path[len(path)-1] == '/' { - // if root wildcard, then add it as it's and return - rootWildcard := path == "/" - if rootWildcard { - path += "/" // if root wildcard, then do it like "//" instead of simple "/" - } - - n := &node{ - rootWildcard: rootWildcard, - s: path, - routeName: routeName, - wildcardParamName: wildcardParamName, - paramNames: paramNames, - handlers: handlers, - root: root, - } - *nodes = append(*nodes, n) - // println("1. nodes.Add path: " + path) - return - - } - -loop: - for _, n := range *nodes { - if n.rootWildcard { - continue - } - - if len(n.paramNames) == 0 && n.wildcardParamName != "" { - continue - } - - minlen := len(n.s) - if len(path) < minlen { - minlen = len(path) - } - - for i := 0; i < minlen; i++ { - if n.s[i] == path[i] { - continue - } - if i == 0 { - continue loop - } - - *n = node{ - s: n.s[:i], - childrenNodes: Nodes{ - { - s: n.s[i:], - routeName: n.routeName, - wildcardParamName: n.wildcardParamName, // wildcardParamName - paramNames: n.paramNames, - childrenNodes: n.childrenNodes, - handlers: n.handlers, - }, - { - s: path[i:], - routeName: routeName, - wildcardParamName: wildcardParamName, - paramNames: paramNames, - handlers: handlers, - }, - }, - root: n.root, - } - - // println("2. change n and return " + n.s[:i] + " and " + path[i:]) - return - } - - if len(path) < len(n.s) { - // println("3. change n and return | n.s[:len(path)] = " + n.s[:len(path)-1] + " and child: " + n.s[len(path)-1:]) - - *n = node{ - s: n.s[:len(path)], - routeName: routeName, - wildcardParamName: wildcardParamName, - paramNames: paramNames, - childrenNodes: Nodes{ - { - s: n.s[len(path):], - routeName: n.routeName, - wildcardParamName: n.wildcardParamName, // wildcardParamName - paramNames: n.paramNames, - childrenNodes: n.childrenNodes, - handlers: n.handlers, - }, - }, - handlers: handlers, - root: n.root, - } - - return - } - - if len(path) > len(n.s) { - if n.wildcardParamName != "" { - n := &node{ - s: path, - routeName: routeName, - wildcardParamName: wildcardParamName, - paramNames: paramNames, - handlers: handlers, - root: root, - } - // println("3.5. nodes.Add path: " + n.s) - *nodes = append(*nodes, n) - return - } - - pathToAdd := path[len(n.s):] - // println("4. nodes.Add route name: " + routeName) - // println("4. nodes.Add path: " + pathToAdd) - err = n.childrenNodes.add(routeName, pathToAdd, paramNames, handlers, false) - return err - } - - if len(handlers) == 0 { // missing handlers - return nil - } - - if len(n.handlers) > 0 { // n.handlers already setted - return ErrDublicate - } - n.paramNames = paramNames - n.handlers = handlers - n.routeName = routeName - return - } - - // START - // Author's note: - // 27 Oct 2017; fixes s|i|l+static+p - // without breaking the current tests. - if wildcardIdx > 0 { - wildcardParamName = path[wildcardIdx+1:] - path = path[0:wildcardIdx-1] + "/" - } - // END - - n := &node{ - s: path, - routeName: routeName, - wildcardParamName: wildcardParamName, - paramNames: paramNames, - handlers: handlers, - root: root, - } - *nodes = append(*nodes, n) - - // println("5. node add on path: " + path + " n.s: " + n.s + " wildcard param: " + n.wildcardParamName) - return -} - -// Find resolves the path, fills its params -// and returns the registered to the resolved node's handlers. -func (nodes Nodes) Find(path string, params *context.RequestParams) (string, context.Handlers) { - n, paramValues := nodes.findChild(path, nil) - if n != nil { - // map the params, - // n.params are the param names - if len(paramValues) > 0 { - // println("-----------") - // print("param values returned len: ") - // println(len(paramValues)) - // println("first value is: " + paramValues[0]) - // print("n.paramNames len: ") - // println(len(n.paramNames)) - for i, name := range n.paramNames { - // println("setting param name: " + name + " = " + paramValues[i]) - params.Set(name, paramValues[i]) - } - // last is the wildcard, - // if paramValues are exceed from the registered param names. - // Note that n.wildcardParamName can be not empty but that doesn't meaning - // that it contains a wildcard path, so the check is required. - if len(paramValues) > len(n.paramNames) { - // println("len(paramValues) > len(n.paramNames)") - lastWildcardVal := paramValues[len(paramValues)-1] - // println("setting wildcard param name: " + n.wildcardParamName + " = " + lastWildcardVal) - params.Set(n.wildcardParamName, lastWildcardVal) - } - } - - return n.routeName, n.handlers - } - - return "", nil -} - -// Exists returns true if a node with that "path" exists, -// otherise false. -// -// We don't care about parameters here. -func (nodes Nodes) Exists(path string) bool { - n, _ := nodes.findChild(path, nil) - return n != nil && len(n.handlers) > 0 -} - -func (nodes Nodes) findChild(path string, params []string) (*node, []string) { - - for _, n := range nodes { - if n.s == ":" { - paramEnd := strings.IndexByte(path, '/') - if paramEnd == -1 { - if len(n.handlers) == 0 { - return nil, nil - } - return n, append(params, path) - } - return n.childrenNodes.findChild(path[paramEnd:], append(params, path[:paramEnd])) - } - - // println("n.s: " + n.s) - // print("n.childrenNodes len: ") - // println(len(n.childrenNodes)) - // print("n.root: ") - // println(n.root) - - // by runtime check of:, - // if n.s == "//" && n.root && n.wildcardParamName != "" { - // but this will slow down, so we have a static field on the node itself: - if n.rootWildcard { - // println("return from n.rootWildcard") - // single root wildcard - if len(path) < 2 { - // do not remove that, it seems useless but it's not, - // we had an error while production, this fixes that. - path = "/" + path - } - return n, append(params, path[1:]) - } - - // second conditional may be unnecessary - // because of the n.rootWildcard before, but do it. - if n.wildcardParamName != "" && len(path) > 2 { - // println("n has wildcard n.s: " + n.s + " on path: " + path) - // n.s = static/, path = static - - // println(n.s + " vs path: " + path) - - // we could have /other/ as n.s so - // we must do this check, remember: - // now wildcards live on their own nodes - if len(path) == len(n.s)-1 { - // then it's like: - // path = /other2 - // ns = /other2/ - if path == n.s[0:len(n.s)-1] { - return n, params - } - } - - // othwerwise path = /other2/dsadas - // ns= /other2/ - if strings.HasPrefix(path, n.s) { - if len(path) > len(n.s)+1 { - return n, append(params, path[len(n.s):]) // without slash - } - } - - } - - if !strings.HasPrefix(path, n.s) { - // fmt.Printf("---here root: %v, n.s: "+n.s+" and path: "+path+" is dynamic: %v , wildcardParamName: %s, children len: %v \n", n.root, n.isDynamic(), n.wildcardParamName, len(n.childrenNodes)) - // println(path + " n.s: " + n.s + " continue...") - continue - } - - if len(path) == len(n.s) { - if len(n.handlers) == 0 { - return nil, nil - } - return n, params - } - - child, childParamNames := n.childrenNodes.findChild(path[len(n.s):], params) - - // print("childParamNames len: ") - // println(len(childParamNames)) - - // if len(childParamNames) > 0 { - // println("childParamsNames[0] = " + childParamNames[0]) - // } - - if child == nil || len(child.handlers) == 0 { - if n.s[len(n.s)-1] == '/' && !(n.root && (n.s == "/" || len(n.childrenNodes) > 0)) { - if len(n.handlers) == 0 { - return nil, nil - } - - // println("if child == nil.... | n.s = " + n.s) - // print("n.paramNames len: ") - // println(n.paramNames) - // print("n.wildcardParamName is: ") - // println(n.wildcardParamName) - // print("return n, append(params, path[len(n.s) | params: ") - // println(path[len(n.s):]) - return n, append(params, path[len(n.s):]) - } - - continue - } - - return child, childParamNames - } - return nil, nil -} - -// childLen returns all the children's and their children's length. -func (n *node) childLen() (i int) { - for _, n := range n.childrenNodes { - i++ - i += n.childLen() - } - return -} - -func (n *node) isDynamic() bool { - return n.s == ":" || n.wildcardParamName != "" || n.rootWildcard -} - -// prioritize sets the static paths first. -func (nodes Nodes) prioritize() { - sort.Slice(nodes, func(i, j int) bool { - if nodes[i].isDynamic() { - return false - } - if nodes[j].isDynamic() { - return true - } - - return nodes[i].childLen() > nodes[j].childLen() - }) - - for _, n := range nodes { - n.childrenNodes.prioritize() - } -} diff --git a/core/router/party.go b/core/router/party.go index 8e8b56bd..5d462392 100644 --- a/core/router/party.go +++ b/core/router/party.go @@ -3,7 +3,7 @@ package router import ( "github.com/kataras/iris/context" "github.com/kataras/iris/core/errors" - "github.com/kataras/iris/core/router/macro" + "github.com/kataras/iris/macro" ) // Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. @@ -18,11 +18,11 @@ type Party interface { GetRelPath() string // GetReporter returns the reporter for adding errors GetReporter() *errors.Reporter - // Macros returns the macro map which is responsible - // to register custom macro functions for all routes. + // Macros returns the macro collection that is responsible + // to register custom macros with their own parameter types and their macro functions for all routes. // // Learn more at: https://github.com/kataras/iris/tree/master/_examples/routing/dynamic-path - Macros() *macro.Map + Macros() *macro.Macros // Party groups routes which may have the same prefix and share same handlers, // returns that new rich subrouter. @@ -110,10 +110,10 @@ type Party interface { // otherwise use `Party` which can handle many paths with different handlers and middlewares. // // Usage: - // app.HandleMany(iris.MethodGet, "/user /user/{id:int} /user/me", userHandler) + // app.HandleMany(iris.MethodGet, "/user /user/{id:uint64} /user/me", userHandler) // At the other side, with `Handle` we've had to write: // app.Handle(iris.MethodGet, "/user", userHandler) - // app.Handle(iris.MethodGet, "/user/{id:int}", userHandler) + // app.Handle(iris.MethodGet, "/user/{id:uint64}", userHandler) // app.Handle(iris.MethodGet, "/user/me", userHandler) // // This method is used behind the scenes at the `Controller` function diff --git a/core/router/path.go b/core/router/path.go index 3a471f90..0a8b4014 100644 --- a/core/router/path.go +++ b/core/router/path.go @@ -7,15 +7,9 @@ import ( "strings" "github.com/kataras/iris/core/netutil" - "github.com/kataras/iris/core/router/macro/interpreter/lexer" -) - -const ( - // ParamStart the character in string representation where the underline router starts its dynamic named parameter. - ParamStart = ":" - // WildcardParamStart the character in string representation where the underline router starts its dynamic wildcard - // path parameter. - WildcardParamStart = "*" + "github.com/kataras/iris/macro" + "github.com/kataras/iris/macro/interpreter/ast" + "github.com/kataras/iris/macro/interpreter/lexer" ) // Param receives a parameter name prefixed with the ParamStart symbol. @@ -31,6 +25,26 @@ func WildcardParam(name string) string { return prefix(name, WildcardParamStart) } +func convertMacroTmplToNodePath(tmpl macro.Template) string { + routePath := tmpl.Src + if len(routePath) > 1 && routePath[len(routePath)-1] == '/' { + routePath = routePath[0 : len(routePath)-1] // remove any last "/" + } + + // if it has started with {} and it's valid + // then the tmpl.Params will be filled, + // so no any further check needed. + for _, p := range tmpl.Params { + if ast.IsTrailing(p.Type) { + routePath = strings.Replace(routePath, p.Src, WildcardParam(p.Name), 1) + } else { + routePath = strings.Replace(routePath, p.Src, Param(p.Name), 1) + } + } + + return routePath +} + func prefix(s string, prefix string) string { if !strings.HasPrefix(s, prefix) { return prefix + s diff --git a/core/router/path_test.go b/core/router/path_test.go index 66ef283b..2c26c6da 100644 --- a/core/router/path_test.go +++ b/core/router/path_test.go @@ -27,8 +27,8 @@ func TestCleanPath(t *testing.T) { "/total/{year:string regexp(\\d{4})}/more/{s:string regexp(\\d{7})}"}, {"/single_no_params", "/single_no_params"}, - {"/single/{id:int}", - "/single/{id:int}"}, + {"/single/{id:uint64}", + "/single/{id:uint64}"}, } for i, tt := range tests { @@ -45,8 +45,10 @@ func TestSplitPath(t *testing.T) { }{ {"/v2/stores/{id:string format(uuid)} /v3", []string{"/v2/stores/{id:string format(uuid)}", "/v3"}}, - {"/user/{id:int} /admin/{id:int}", - []string{"/user/{id:int}", "/admin/{id:int}"}}, + {"/user/{id:uint64} /admin/{id:uint64}", + []string{"/user/{id:uint64}", "/admin/{id:uint64}"}}, + {"/users/{id:int} /admins/{id:int64}", + []string{"/users/{id:int}", "/admins/{id:int64}"}}, {"/user /admin", []string{"/user", "/admin"}}, {"/single_no_params", diff --git a/core/router/route.go b/core/router/route.go index 6c4918f1..132eb7c7 100644 --- a/core/router/route.go +++ b/core/router/route.go @@ -5,18 +5,19 @@ import ( "strings" "github.com/kataras/iris/context" - "github.com/kataras/iris/core/router/macro" + "github.com/kataras/iris/macro" + "github.com/kataras/iris/macro/handler" ) // Route contains the information about a registered Route. // If any of the following fields are changed then the // caller should Refresh the router. type Route struct { - Name string `json:"name"` // "userRoute" - Method string `json:"method"` // "GET" - methodBckp string // if Method changed to something else (which is possible at runtime as well, via RefreshRouter) then this field will be filled with the old one. - Subdomain string `json:"subdomain"` // "admin." - tmpl *macro.Template // Tmpl().Src: "/api/user/{id:int}" + Name string `json:"name"` // "userRoute" + Method string `json:"method"` // "GET" + methodBckp string // if Method changed to something else (which is possible at runtime as well, via RefreshRouter) then this field will be filled with the old one. + Subdomain string `json:"subdomain"` // "admin." + tmpl macro.Template // Tmpl().Src: "/api/user/{id:uint64}" // temp storage, they're appended to the Handlers on build. // Execution happens before Handlers, can be empty. beginHandlers context.Handlers @@ -39,16 +40,19 @@ type Route struct { // It parses the path based on the "macros", // handlers are being changed to validate the macros at serve time, if needed. func NewRoute(method, subdomain, unparsedPath, mainHandlerName string, - handlers context.Handlers, macros *macro.Map) (*Route, error) { + handlers context.Handlers, macros macro.Macros) (*Route, error) { tmpl, err := macro.Parse(unparsedPath, macros) if err != nil { return nil, err } - path, handlers, err := compileRoutePathAndHandlers(handlers, tmpl) - if err != nil { - return nil, err + path := convertMacroTmplToNodePath(tmpl) + // prepend the macro handler to the route, now, + // right before the register to the tree, so APIBuilder#UseGlobal will work as expected. + if handler.CanMakeHandler(tmpl) { + macroEvaluatorHandler := handler.MakeHandler(tmpl) + handlers = append(context.Handlers{macroEvaluatorHandler}, handlers...) } path = cleanPath(path) // maybe unnecessary here but who cares in this moment @@ -152,7 +156,18 @@ func (r Route) String() string { // via Tmpl().Src, Route.Path is the path // converted to match the underline router's specs. func (r Route) Tmpl() macro.Template { - return *r.tmpl + return r.tmpl +} + +// RegisteredHandlersLen returns the end-developer's registered handlers, all except the macro evaluator handler +// if was required by the build process. +func (r Route) RegisteredHandlersLen() int { + n := len(r.Handlers) + if handler.CanMakeHandler(r.tmpl) { + n-- + } + + return n } // IsOnline returns true if the route is marked as "online" (state). @@ -198,7 +213,7 @@ func formatPath(path string) string { // StaticPath returns the static part of the original, registered route path. // if /user/{id} it will return /user -// if /user/{id}/friend/{friendid:int} it will return /user too +// if /user/{id}/friend/{friendid:uint64} it will return /user too // if /assets/{filepath:path} it will return /assets. func (r Route) StaticPath() string { src := r.tmpl.Src @@ -242,7 +257,8 @@ func (r Route) Trace() string { printfmt += fmt.Sprintf(" %s", r.Subdomain) } printfmt += fmt.Sprintf(" %s ", r.Tmpl().Src) - if l := len(r.Handlers); l > 1 { + + if l := r.RegisteredHandlersLen(); l > 1 { printfmt += fmt.Sprintf("-> %s() and %d more", r.MainHandlerName, l-1) } else { printfmt += fmt.Sprintf("-> %s()", r.MainHandlerName) diff --git a/core/router/router.go b/core/router/router.go index 50526395..f4e9840d 100644 --- a/core/router/router.go +++ b/core/router/router.go @@ -31,7 +31,7 @@ func NewRouter() *Router { return &Router{} } // RefreshRouter re-builds the router. Should be called when a route's state // changed (i.e Method changed at serve-time). func (router *Router) RefreshRouter() error { - return router.BuildRouter(router.cPool, router.requestHandler, router.routesProvider) + return router.BuildRouter(router.cPool, router.requestHandler, router.routesProvider, true) } // BuildRouter builds the router based on @@ -41,7 +41,7 @@ func (router *Router) RefreshRouter() error { // its wrapper. // // Use of RefreshRouter to re-build the router if needed. -func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHandler, routesProvider RoutesProvider) error { +func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHandler, routesProvider RoutesProvider, force bool) error { if requestHandler == nil { return errors.New("router: request handler is nil") @@ -60,9 +60,23 @@ func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHan defer router.mu.Unlock() // store these for RefreshRouter's needs. - router.cPool = cPool - router.requestHandler = requestHandler - router.routesProvider = routesProvider + if force { + router.cPool = cPool + router.requestHandler = requestHandler + router.routesProvider = routesProvider + } else { + if router.cPool == nil { + router.cPool = cPool + } + + if router.requestHandler == nil { + router.requestHandler = requestHandler + } + + if router.routesProvider == nil && routesProvider != nil { + router.routesProvider = routesProvider + } + } // the important router.mainHandler = func(w http.ResponseWriter, r *http.Request) { diff --git a/core/router/router_wildcard_root_test.go b/core/router/router_wildcard_root_test.go index 110192eb..c3190ce5 100644 --- a/core/router/router_wildcard_root_test.go +++ b/core/router/router_wildcard_root_test.go @@ -122,20 +122,25 @@ func TestRouterWildcardRootMany(t *testing.T) { func TestRouterWildcardRootManyAndRootStatic(t *testing.T) { var tt = []testRoute{ - // all routes will be handlded by "h" because we added wildcard to root, + // routes that may return 404 will be handled by the below route ("h" handler) because we added wildcard to root, // this feature is very important and can remove noumerous of previous hacks on our apps. + // + // Static paths and parameters have priority over wildcard, all three types can be registered in the same path prefix. + // + // Remember, all of those routes are registered don't be tricked by the visual appearance of the below test blocks. {"GET", "/{p:path}", h, []testRouteRequest{ {"GET", "", "/other2almost/some", iris.StatusOK, same_as_request_path}, }}, {"GET", "/static/{p:path}", h, []testRouteRequest{ - {"GET", "", "/static", iris.StatusOK, same_as_request_path}, + {"GET", "", "/static", iris.StatusOK, same_as_request_path}, // HERE<- IF NOT FOUND THEN BACKWARDS TO WILDCARD IF THERE IS ONE, HMM. {"GET", "", "/static/something/here", iris.StatusOK, same_as_request_path}, }}, {"GET", "/", h, []testRouteRequest{ {"GET", "", "/", iris.StatusOK, same_as_request_path}, }}, {"GET", "/other/{paramother:path}", h2, []testRouteRequest{ - {"GET", "", "/other", iris.StatusForbidden, same_as_request_path}, + // OK and not h2 because of the root wildcard. + {"GET", "", "/other", iris.StatusOK, same_as_request_path}, {"GET", "", "/other/wildcard", iris.StatusForbidden, same_as_request_path}, {"GET", "", "/other/wildcard/here", iris.StatusForbidden, same_as_request_path}, }}, @@ -145,6 +150,7 @@ func TestRouterWildcardRootManyAndRootStatic(t *testing.T) { }}, {"GET", "/other2/static", h3, []testRouteRequest{ {"GET", "", "/other2/static", iris.StatusOK, prefix_static_path_following_by_request_path}, + // h2(Forbiddenn) instead of h3 OK because it will be handled by the /other2/{paramothersecond:path}'s handler which gives 403. {"GET", "", "/other2/staticed", iris.StatusForbidden, same_as_request_path}, }}, } @@ -165,6 +171,7 @@ func testTheRoutes(t *testing.T, tests []testRoute, debug bool) { // run the tests for _, tt := range tests { for _, req := range tt.requests { + // t.Logf("req: %s:%s\n", tt.method, tt.path) method := req.method if method == "" { method = tt.method diff --git a/core/router/trie.go b/core/router/trie.go new file mode 100644 index 00000000..9e98efbb --- /dev/null +++ b/core/router/trie.go @@ -0,0 +1,268 @@ +package router + +import ( + "strings" + + "github.com/kataras/iris/context" +) + +const ( + // ParamStart the character in string representation where the underline router starts its dynamic named parameter. + ParamStart = ":" + // WildcardParamStart the character in string representation where the underline router starts its dynamic wildcard + // path parameter. + WildcardParamStart = "*" +) + +// An iris-specific identical version of the https://github.com/kataras/muxie version 1.0.0 released at 15 Oct 2018 +type trieNode struct { + parent *trieNode + + children map[string]*trieNode + hasDynamicChild bool // does one of the children contains a parameter or wildcard? + childNamedParameter bool // is the child a named parameter (single segmnet) + childWildcardParameter bool // or it is a wildcard (can be more than one path segments) ? + paramKeys []string // the param keys without : or *. + end bool // it is a complete node, here we stop and we can say that the node is valid. + key string // if end == true then key is filled with the original value of the insertion's key. + // if key != "" && its parent has childWildcardParameter == true, + // we need it to track the static part for the closest-wildcard's parameter storage. + staticKey string + + // insert data. + Handlers context.Handlers + RouteName string +} + +func newTrieNode() *trieNode { + n := new(trieNode) + return n +} + +func (tn *trieNode) hasChild(s string) bool { + return tn.getChild(s) != nil +} + +func (tn *trieNode) getChild(s string) *trieNode { + if tn.children == nil { + tn.children = make(map[string]*trieNode) + } + + return tn.children[s] +} + +func (tn *trieNode) addChild(s string, n *trieNode) { + if tn.children == nil { + tn.children = make(map[string]*trieNode) + } + + if _, exists := tn.children[s]; exists { + return + } + + n.parent = tn + tn.children[s] = n +} + +func (tn *trieNode) findClosestParentWildcardNode() *trieNode { + tn = tn.parent + for tn != nil { + if tn.childWildcardParameter { + return tn.getChild(WildcardParamStart) + } + + tn = tn.parent + } + + return nil +} + +func (tn *trieNode) String() string { + return tn.key +} + +type trie struct { + root *trieNode + + // if true then it will handle any path if not other parent wildcard exists, + // so even 404 (on http services) is up to it, see trie#insert. + hasRootWildcard bool + + method string + // subdomain is empty for default-hostname routes, + // ex: mysubdomain. + subdomain string +} + +func newTrie() *trie { + return &trie{ + root: newTrieNode(), + } +} + +const ( + pathSep = "/" + pathSepB = '/' +) + +func slowPathSplit(path string) []string { + if path == "/" { + return []string{"/"} + } + + return strings.Split(path, pathSep)[1:] +} + +func (tr *trie) insert(path, routeName string, handlers context.Handlers) { + input := slowPathSplit(path) + + n := tr.root + var paramKeys []string + + for _, s := range input { + c := s[0] + + if isParam, isWildcard := c == ParamStart[0], c == WildcardParamStart[0]; isParam || isWildcard { + n.hasDynamicChild = true + paramKeys = append(paramKeys, s[1:]) // without : or *. + + // if node has already a wildcard, don't force a value, check for true only. + if isParam { + n.childNamedParameter = true + s = ParamStart + } + + if isWildcard { + n.childWildcardParameter = true + s = WildcardParamStart + if tr.root == n { + tr.hasRootWildcard = true + } + } + } + + if !n.hasChild(s) { + child := newTrieNode() + n.addChild(s, child) + } + + n = n.getChild(s) + } + + n.RouteName = routeName + n.Handlers = handlers + n.paramKeys = paramKeys + n.key = path + n.end = true + + i := strings.Index(path, ParamStart) + if i == -1 { + i = strings.Index(path, WildcardParamStart) + } + if i == -1 { + i = len(n.key) + } + + n.staticKey = path[:i] +} + +func (tr *trie) search(q string, params *context.RequestParams) *trieNode { + end := len(q) + + if end == 0 || (end == 1 && q[0] == pathSepB) { + return tr.root.getChild(pathSep) + } + + n := tr.root + start := 1 + i := 1 + var paramValues []string + + for { + if i == end || q[i] == pathSepB { + if child := n.getChild(q[start:i]); child != nil { + n = child + } else if n.childNamedParameter { + n = n.getChild(ParamStart) + if ln := len(paramValues); cap(paramValues) > ln { + paramValues = paramValues[:ln+1] + paramValues[ln] = q[start:i] + } else { + paramValues = append(paramValues, q[start:i]) + } + } else if n.childWildcardParameter { + n = n.getChild(WildcardParamStart) + if ln := len(paramValues); cap(paramValues) > ln { + paramValues = paramValues[:ln+1] + paramValues[ln] = q[start:] + } else { + paramValues = append(paramValues, q[start:]) + } + break + } else { + n = n.findClosestParentWildcardNode() + if n != nil { + // means that it has :param/static and *wildcard, we go trhough the :param + // but the next path segment is not the /static, so go back to *wildcard + // instead of not found. + // + // Fixes: + // /hello/*p + // /hello/:p1/static/:p2 + // req: http://localhost:8080/hello/dsadsa/static/dsadsa => found + // req: http://localhost:8080/hello/dsadsa => but not found! + // and + // /second/wild/*p + // /second/wild/static/otherstatic/ + // req: /second/wild/static/otherstatic/random => but not found! + params.Set(n.paramKeys[0], q[len(n.staticKey):]) + return n + } + + return nil + } + + if i == end { + break + } + + i++ + start = i + continue + } + + i++ + } + + if n == nil || !n.end { + if n != nil { // we need it on both places, on last segment (below) or on the first unnknown (above). + if n = n.findClosestParentWildcardNode(); n != nil { + params.Set(n.paramKeys[0], q[len(n.staticKey):]) + return n + } + } + + if tr.hasRootWildcard { + // that's the case for root wildcard, tests are passing + // even without it but stick with it for reference. + // Note ote that something like: + // Routes: /other2/*myparam and /other2/static + // Reqs: /other2/staticed will be handled + // the /other2/*myparam and not the root wildcard, which is what we want. + // + n = tr.root.getChild(WildcardParamStart) + params.Set(n.paramKeys[0], q[1:]) + return n + } + + return nil + } + + for i, paramValue := range paramValues { + if len(n.paramKeys) > i { + params.Set(n.paramKeys[i], paramValue) + } + } + + return n +} diff --git a/deprecated.go b/deprecated.go deleted file mode 100644 index d44707b2..00000000 --- a/deprecated.go +++ /dev/null @@ -1 +0,0 @@ -package iris diff --git a/doc.go b/doc.go index 00a781ae..6c8bb567 100644 --- a/doc.go +++ b/doc.go @@ -35,11 +35,11 @@ Source code and other details for the project are available at GitHub: Current Version -10.7.0 +11.0.0 Installation -The only requirement is the Go Programming Language, at least version 1.8 but 1.10 and above is highly recommended. +The only requirement is the Go Programming Language, at least version 1.8 but 1.11.1 and above is highly recommended. $ go get -u github.com/kataras/iris @@ -119,7 +119,7 @@ Example code: usersRoutes := app.Party("/users", logThisMiddleware) { // Method GET: http://localhost:8080/users/42 - usersRoutes.Get("/{id:int min(1)}", getUserByID) + usersRoutes.Get("/{id:uint64 min(1)}", getUserByID) // Method POST: http://localhost:8080/users/create usersRoutes.Post("/create", createUser) } @@ -146,7 +146,7 @@ Example code: } func getUserByID(ctx iris.Context) { - userID := ctx.Params().Get("id") // Or convert directly using: .Values().GetInt/GetInt64 etc... + userID := ctx.Params().Get("id") // Or convert directly using: .Values().GetInt/GetUint64/GetInt64 etc... // your own db fetch here instead of user :=... user := User{Username: "username" + userID} @@ -489,7 +489,7 @@ Example code: users := app.Party("/users", myAuthMiddlewareHandler) // http://myhost.com/users/42/profile - users.Get("/{id:int}/profile", userProfileHandler) + users.Get("/{id:uint64}/profile", userProfileHandler) // http://myhost.com/users/messages/1 users.Get("/inbox/{id:int}", userMessageHandler) @@ -548,8 +548,8 @@ Example code: app.Get("/donate", donateHandler, donateFinishHandler) // Pssst, don't forget dynamic-path example for more "magic"! - app.Get("/api/users/{userid:int min(1)}", func(ctx iris.Context) { - userID, err := ctx.Params().GetInt("userid") + app.Get("/api/users/{userid:uint64 min(1)}", func(ctx iris.Context) { + userID, err := ctx.Params().GetUint64("userid") if err != nil { ctx.Writef("error while trying to parse userid parameter," + @@ -622,8 +622,8 @@ Example code: ctx.Writef("All users") }) // http://v1.localhost:8080/api/users/42 - usersAPI.Get("/{userid:int}", func(ctx iris.Context) { - ctx.Writef("user with id: %s", ctx.Params().Get("userid")) + usersAPI.Get("/{userid:uint64}", func(ctx iris.Context) { + ctx.Writef("user with id: %s", ctx.Params().GetUint64("userid")) }) } } @@ -709,23 +709,71 @@ Standard macro types for parameters: | {param:string} | +------------------------+ string type - anything + anything (single path segmnent) - +------------------------+ - | {param:int} | - +------------------------+ + +-------------------------------+ + | {param:int} | + +-------------------------------+ int type - only numbers (0-9) + -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch +------------------------+ - | {param:long} | + | {param:int8} | + +------------------------+ + int8 type + -128 to 127 + + +------------------------+ + | {param:int16} | + +------------------------+ + int16 type + -32768 to 32767 + + +------------------------+ + | {param:int32} | + +------------------------+ + int32 type + -2147483648 to 2147483647 + + +------------------------+ + | {param:int64} | +------------------------+ int64 type - only numbers (0-9) + -9223372036854775808 to 9223372036854775807 +------------------------+ - | {param:boolean} | + | {param:uint} | +------------------------+ + uint type + 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32) + + +------------------------+ + | {param:uint8} | + +------------------------+ + uint8 type + 0 to 255 + + +------------------------+ + | {param:uint16} | + +------------------------+ + uint16 type + 0 to 65535 + + +------------------------+ + | {param:uint32} | + +------------------------+ + uint32 type + 0 to 4294967295 + + +------------------------+ + | {param:uint64} | + +------------------------+ + uint64 type + 0 to 18446744073709551615 + + +---------------------------------+ + | {param:bool} or {param:boolean} | + +---------------------------------+ bool type only "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False" @@ -751,8 +799,8 @@ Standard macro types for parameters: | {param:path} | +------------------------+ path type - anything, should be the last part, more than one path segment, - i.e: /path1/path2/path3 , ctx.Params().Get("param") == "/path1/path2/path3" + anything, should be the last part, can be more than one path segment, + i.e: "/test/*param" and request: "/test/path1/path2/path3" , ctx.Params().Get("param") == "path1/path2/path3" if type is missing then parameter's type is defaulted to string, so {param} == {param:string}. @@ -770,16 +818,18 @@ you are able to register your own too!. Register a named path parameter function: - app.Macros().Int.RegisterFunc("min", func(argument int) func(paramValue string) bool { - [...] - return true/false -> true means valid. + app.Macros().Get("int").RegisterFunc("min", func(argument int) func(paramValue int) bool { + return func(paramValue int) bool { + [...] + return true/false -> true means valid. + } }) at the func(argument ...) you can have any standard type, it will be validated before the server starts so don't care about performance here, the only thing it runs at serve time is the returning func(paramValue string) bool. {param:string equal(iris)} , "iris" will be the argument here: - app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool { + app.Macros().Get("string").RegisterFunc("equal", func(argument string) func(paramValue string) bool { return func(paramValue string){ return argument == paramValue } }) @@ -795,38 +845,34 @@ Example Code: // Let's register our first macro attached to int macro type. // "min" = the function // "minValue" = the argument of the function - // func(string) bool = the macro's path parameter evaluator, this executes in serve time when - // a user requests a path which contains the :int macro type with the min(...) macro parameter function. - app.Macros().Int.RegisterFunc("min", func(minValue int) func(string) bool { + // func() bool = the macro's path parameter evaluator, this executes in serve time when + // a user requests a path which contains the int macro type with the min(...) macro parameter function. + app.Macros().Get("int").RegisterFunc("min", func(minValue int) func(int) bool { // do anything before serve here [...] // at this case we don't need to do anything - return func(paramValue string) bool { - n, err := strconv.Atoi(paramValue) - if err != nil { - return false - } - return n >= minValue + return func(paramValue int) bool { + return paramValue >= minValue } }) // http://localhost:8080/profile/id>=1 // this will throw 404 even if it's found as route on : /profile/0, /profile/blabla, /profile/-1 // macro parameter functions are optional of course. - app.Get("/profile/{id:int min(1)}", func(ctx iris.Context) { + app.Get("/profile/{id:uint64 min(1)}", func(ctx iris.Context) { // second parameter is the error but it will always nil because we use macros, // the validaton already happened. - id, _ := ctx.Params().GetInt("id") + id, _ := ctx.Params().GetUint64("id") ctx.Writef("Hello id: %d", id) }) // to change the error code per route's macro evaluator: - app.Get("/profile/{id:int min(1)}/friends/{friendid:int min(1) else 504}", func(ctx iris.Context) { - id, _ := ctx.Params().GetInt("id") - friendid, _ := ctx.Params().GetInt("friendid") + app.Get("/profile/{id:uint64 min(1)}/friends/{friendid:uint64 min(1) else 504}", func(ctx iris.Context) { + id, _ := ctx.Params().GetUint64("id") + friendid, _ := ctx.Params().GetUint64("friendid") ctx.Writef("Hello id: %d looking for friend id: ", id, friendid) }) // this will throw e 504 error code instead of 404 if all route's macros not passed. - // http://localhost:8080/game/a-zA-Z/level/0-9 + // http://localhost:8080/game/a-zA-Z/level/42 // remember, alphabetical is lowercase or uppercase letters only. app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx iris.Context) { ctx.Writef("name: %s | level: %s", ctx.Params().Get("name"), ctx.Params().Get("level")) @@ -855,11 +901,6 @@ Example Code: } - -A path parameter name should contain only alphabetical letters, symbols, containing '_' and numbers are NOT allowed. -If route failed to be registered, the app will panic without any warnings -if you didn't catch the second return value(error) on .Handle/.Get.... - Last, do not confuse ctx.Values() with ctx.Params(). Path parameter's values goes to ctx.Params() and context's local storage that can be used to communicate between handlers and middleware(s) goes to diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..8711dc12 --- /dev/null +++ b/go.mod @@ -0,0 +1,68 @@ +module github.com/kataras/iris + +require ( + github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7 // indirect + github.com/BurntSushi/toml v0.3.1 + github.com/Joker/jade v0.7.0 + github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc + github.com/ajg/form v0.0.0-20160822230020-523a5da1a92f // indirect + github.com/aymerick/raymond v2.0.2+incompatible + github.com/boltdb/bolt v1.3.1 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dgraph-io/badger v1.5.4 + github.com/dgryski/go-farm v0.0.0-20180109070241-2de33835d102 // indirect + github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385 + github.com/etcd-io/bbolt v1.3.0 + github.com/fatih/structs v1.0.0 + github.com/flosch/pongo2 v0.0.0-20180809100617-24195e6d38b0 + github.com/gavv/monotime v0.0.0-20171021193802-6f8212e8d10d // indirect + github.com/gomodule/redigo v2.0.0+incompatible + github.com/google/go-querystring v1.0.0 // indirect + github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c // indirect + github.com/gorilla/websocket v1.4.0 + github.com/imkira/go-interpol v1.1.0 // indirect + github.com/iris-contrib/formBinder v0.0.0-20171010160137-ad9fb86c356f + github.com/iris-contrib/go.uuid v2.0.0+incompatible + github.com/iris-contrib/httpexpect v0.0.0-20180314041918-ebe99fcebbce + github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0 + github.com/json-iterator/go v1.1.5 + github.com/jtolds/gls v4.2.1+incompatible // indirect + github.com/juju/errors v0.0.0-20180806074554-22422dad46e1 // indirect + github.com/juju/loggo v0.0.0-20180524022052-584905176618 // indirect + github.com/juju/testing v0.0.0-20180920084828-472a3e8b2073 // indirect + github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect + github.com/kataras/golog v0.0.0-20180321173939-03be10146386 + github.com/kataras/pio v0.0.0-20180511174041-a9733b5b6b83 // indirect + github.com/klauspost/compress v1.4.0 + github.com/klauspost/cpuid v0.0.0-20180405133222-e7e905edc00e // indirect + github.com/mattn/go-colorable v0.0.9 // indirect + github.com/mattn/go-isatty v0.0.4 // indirect + github.com/microcosm-cc/bluemonday v1.0.1 + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.1 // indirect + github.com/moul/http2curl v0.0.0-20170919181001-9ac6cf4d929b // indirect + github.com/onsi/gomega v1.4.2 // indirect + github.com/pkg/errors v0.8.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/ryanuber/columnize v2.1.0+incompatible + github.com/sergi/go-diff v1.0.0 // indirect + github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95 // indirect + github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect + github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a // indirect + github.com/stretchr/testify v1.2.2 // indirect + github.com/valyala/bytebufferpool v1.0.0 + github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xeipuuv/gojsonschema v0.0.0-20180816142147-da425ebb7609 // indirect + github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect + github.com/yudai/gojsondiff v1.0.0 // indirect + github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect + github.com/yudai/pp v2.0.1+incompatible // indirect + golang.org/x/crypto v0.0.0-20180927165925-5295e8364332 + golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3 // indirect + golang.org/x/sys v0.0.0-20180928133829-e4b3c5e90611 // indirect + gopkg.in/ini.v1 v1.38.3 // indirect + gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce // indirect + gopkg.in/russross/blackfriday.v2 v2.0.0+incompatible + gopkg.in/yaml.v2 v2.2.1 +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..40e48054 --- /dev/null +++ b/go.sum @@ -0,0 +1,148 @@ +github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7 h1:PqzgE6kAMi81xWQA2QIVxjWkFHptGgC547vchpUbtFo= +github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Joker/jade v0.7.0 h1:9sEpF/GAfkn0D0n+x8/SVGpxvdjIStsyPaTvtXW6z/U= +github.com/Joker/jade v0.7.0/go.mod h1:R1kvvouJogE6SnKqO5Qw3j2rCE2T9HjIWaFeSET/qMQ= +github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc h1:zZYkIbeMNcH1lhztdVxy4+Ykk8NoMhqUfSigsrT/x7Y= +github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= +github.com/ajg/form v0.0.0-20160822230020-523a5da1a92f h1:zvClvFQwU++UpIUBGC8YmDlfhUrweEy1R1Fj1gu5iIM= +github.com/ajg/form v0.0.0-20160822230020-523a5da1a92f/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= +github.com/aymerick/raymond v2.0.2+incompatible h1:VEp3GpgdAnv9B2GFyTvqgcKvY+mfKMjPOA3SbKLtnU0= +github.com/aymerick/raymond v2.0.2+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= +github.com/boltdb/bolt v1.3.1 h1:JQmyP4ZBrce+ZQu0dY660FMfatumYDLun9hBCUVIkF4= +github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgraph-io/badger v1.5.4 h1:gVTrpUTbbr/T24uvoCaqY2KSHfNLVGm0w+hbee2HMeg= +github.com/dgraph-io/badger v1.5.4/go.mod h1:VZxzAIRPHRVNRKRo6AXrX9BJegn6il06VMTZVJYCIjQ= +github.com/dgryski/go-farm v0.0.0-20180109070241-2de33835d102 h1:afESQBXJEnj3fu+34X//E8Wg3nEbMJxJkwSc0tPePK0= +github.com/dgryski/go-farm v0.0.0-20180109070241-2de33835d102/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385 h1:clC1lXBpe2kTj2VHdaIu9ajZQe4kcEY9j0NsnDDBZ3o= +github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= +github.com/etcd-io/bbolt v1.3.0 h1:ec0U3x11Mk69A8YwQyZEhNaUqHkQSv2gDR3Bioz5DfU= +github.com/etcd-io/bbolt v1.3.0/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= +github.com/fatih/structs v1.0.0 h1:BrX964Rv5uQ3wwS+KRUAJCBBw5PQmgJfJ6v4yly5QwU= +github.com/fatih/structs v1.0.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/flosch/pongo2 v0.0.0-20180809100617-24195e6d38b0 h1:ZHx2BEERvWkuwuE7qWN9TuRxucHDH2JrsvneZjVJfo0= +github.com/flosch/pongo2 v0.0.0-20180809100617-24195e6d38b0/go.mod h1:rE0ErqqBaMcp9pzj8JxV1GcfDBpuypXYxlR1c37AUwg= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/gavv/monotime v0.0.0-20171021193802-6f8212e8d10d h1:oYXrtNhqNKL1dVtKdv8XUq5zqdGVFNQ0/4tvccXZOLM= +github.com/gavv/monotime v0.0.0-20171021193802-6f8212e8d10d/go.mod h1:vmp8DIyckQMXOPl0AQVHt+7n5h7Gb7hS6CUydiV8QeA= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c h1:16eHWuMGvCjSfgRJKqIzapE78onvvTbdi1rMkU00lZw= +github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk= +github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= +github.com/iris-contrib/formBinder v0.0.0-20171010160137-ad9fb86c356f h1:WgD6cqCSncBgkftw34mSPlMKU5JgoruAomW/SJtRrGU= +github.com/iris-contrib/formBinder v0.0.0-20171010160137-ad9fb86c356f/go.mod h1:i8kTYUOEstd/S8TG0ChTXQdf4ermA/e8vJX0+QruD9w= +github.com/iris-contrib/go.uuid v2.0.0+incompatible h1:XZubAYg61/JwnJNbZilGjf3b3pB80+OQg2qf6c8BfWE= +github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= +github.com/iris-contrib/httpexpect v0.0.0-20180314041918-ebe99fcebbce h1:q8Ka/exfHNgK7izJE+aUOZd7KZXJ7oQbnJWiZakEiMo= +github.com/iris-contrib/httpexpect v0.0.0-20180314041918-ebe99fcebbce/go.mod h1:VER17o2JZqquOx41avolD/wMGQSFEFBKWmhag9/RQRY= +github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0 h1:Kyp9KiXwsyZRTeoNjgVCrWks7D8ht9+kg6yCjh8K97o= +github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0/go.mod h1:pMCz62A0xJL6I+umB2YTlFRwWXaDFA0jy+5HzGiJjqI= +github.com/json-iterator/go v1.1.5 h1:gL2yXlmiIo4+t+y32d4WGwOjKGYcGOuyrg46vadswDE= +github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/jtolds/gls v4.2.1+incompatible h1:fSuqC+Gmlu6l/ZYAoZzx2pyucC8Xza35fpRVWLVmUEE= +github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/juju/errors v0.0.0-20180806074554-22422dad46e1 h1:wnhMXidtb70kDZCeLt/EfsVtkXS5c8zLnE9y/6DIRAU= +github.com/juju/errors v0.0.0-20180806074554-22422dad46e1/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= +github.com/juju/loggo v0.0.0-20180524022052-584905176618 h1:MK144iBQF9hTSwBW/9eJm034bVoG30IshVm688T2hi8= +github.com/juju/loggo v0.0.0-20180524022052-584905176618/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U= +github.com/juju/testing v0.0.0-20180920084828-472a3e8b2073 h1:WQM1NildKThwdP7qWrNAFGzp4ijNLw8RlgENkaI4MJs= +github.com/juju/testing v0.0.0-20180920084828-472a3e8b2073/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA= +github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 h1:uC1QfSlInpQF+M0ao65imhwqKnz3Q2z/d8PWZRMQvDM= +github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= +github.com/kataras/golog v0.0.0-20180321173939-03be10146386 h1:VT6AeCHO/mc+VedKBMhoqb5eAK8B1i9F6nZl7EGlHvA= +github.com/kataras/golog v0.0.0-20180321173939-03be10146386/go.mod h1:PcaEvfvhGsqwXZ6S3CgCbmjcp+4UDUh2MIfF2ZEul8M= +github.com/kataras/pio v0.0.0-20180511174041-a9733b5b6b83 h1:NoJ+fI58ptwrPc1blX116i+5xWGAY/2TJww37AN8X54= +github.com/kataras/pio v0.0.0-20180511174041-a9733b5b6b83/go.mod h1:NV88laa9UiiDuX9AhMbDPkGYSPugBOV6yTZB1l2K9Z0= +github.com/klauspost/compress v1.4.0 h1:8nsMz3tWa9SWWPL60G1V6CUsf4lLjWLTNEtibhe8gh8= +github.com/klauspost/compress v1.4.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/cpuid v0.0.0-20180405133222-e7e905edc00e h1:+lIPJOWl+jSiJOc70QXJ07+2eg2Jy2EC7Mi11BWujeM= +github.com/klauspost/cpuid v0.0.0-20180405133222-e7e905edc00e/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= +github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs= +github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/microcosm-cc/bluemonday v1.0.1 h1:SIYunPjnlXcW+gVfvm0IlSeR5U3WZUOLfVmqg85Go44= +github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/moul/http2curl v0.0.0-20170919181001-9ac6cf4d929b h1:Pip12xNtMvEFUBF4f8/b5yRXj94LLrNdLWELfOr2KcY= +github.com/moul/http2curl v0.0.0-20170919181001-9ac6cf4d929b/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= +github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.4.2 h1:3mYCb7aPxS/RU7TI1y4rkEn1oKmPRjNJLNEXgw7MH2I= +github.com/onsi/gomega v1.4.2/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/ryanuber/columnize v2.1.0+incompatible h1:j1Wcmh8OrK4Q7GXY+V7SVSY8nUWQxHW5TkBe7YUl+2s= +github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95 h1:/vdW8Cb7EXrkqWGufVMES1OH2sU9gKVb2n9/1y5NMBY= +github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a h1:JSvGDIbmil4Ui/dDdFBExb7/cmkNjyX5F97oglmvCDo= +github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v0.0.0-20180816142147-da425ebb7609 h1:BcMExZAULPkihVZ7UJXK7t8rwGqisXFw75tILnafhBY= +github.com/xeipuuv/gojsonschema v0.0.0-20180816142147-da425ebb7609/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= +github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY= +github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI= +github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA= +github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M= +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= +github.com/yudai/pp v2.0.1+incompatible h1:Q4//iY4pNF6yPLZIigmvcl7k/bPgrcTPIFIcmawg5bI= +github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc= +golang.org/x/crypto v0.0.0-20180927165925-5295e8364332 h1:hvQVdF6P9DX4OiKA5tpehlG6JsgzmyQiThG7q5Bn3UQ= +golang.org/x/crypto v0.0.0-20180927165925-5295e8364332/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3 h1:dgd4x4kJt7G4k4m93AYLzM8Ni6h2qLTfh9n9vXJT3/0= +golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180928133829-e4b3c5e90611 h1:O33LKL7WyJgjN9CvxfTIomjIClbd/Kq86/iipowHQU0= +golang.org/x/sys v0.0.0-20180928133829-e4b3c5e90611/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/ini.v1 v1.38.3 h1:ourkRZgR6qjJYoec9lYhX4+nuN1tEbV34dQEQ3IRk9U= +gopkg.in/ini.v1 v1.38.3/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce h1:xcEWjVhvbDy+nHP67nPDDpbYrY+ILlfndk4bRioVHaU= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/russross/blackfriday.v2 v2.0.0+incompatible h1:l1Mna0cVh8WlpyB8uFtc2c+5cdvrI5CDyuwTgIChojI= +gopkg.in/russross/blackfriday.v2 v2.0.0+incompatible/go.mod h1:6sSBNz/GtOm/pJTuh5UmBK2ZHfmnxGbl2NZg1UliSOI= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/hero/di.go b/hero/di.go index 4244cfa0..d5066514 100644 --- a/hero/di.go +++ b/hero/di.go @@ -8,6 +8,17 @@ import ( func init() { di.DefaultHijacker = func(fieldOrFuncInput reflect.Type) (*di.BindObject, bool) { + // if IsExpectingStore(fieldOrFuncInput) { + // return &di.BindObject{ + // Type: memstoreTyp, + // BindType: di.Dynamic, + // ReturnValue: func(ctxValue []reflect.Value) reflect.Value { + // // return ctxValue[0].MethodByName("Params").Call(di.EmptyIn)[0] + // return ctxValue[0].MethodByName("Params").Call(di.EmptyIn)[0].Field(0) // the Params' memstore.Store. + // }, + // }, true + // } + if !IsContext(fieldOrFuncInput) { return nil, false } diff --git a/hero/di/func.go b/hero/di/func.go index da81d6f3..3c417d8f 100644 --- a/hero/di/func.go +++ b/hero/di/func.go @@ -132,9 +132,8 @@ func (s *FuncInjector) addValue(inputIndex int, value reflect.Value) bool { } if b.IsAssignable(inTyp) { - // println(inTyp.String() + " is assignable to " + val.Type().String()) // fmt.Printf("binded input index: %d for type: %s and value: %v with pointer: %v\n", - // i, b.Type.String(), value.String(), val.Pointer()) + // i, b.Type.String(), inTyp.String(), inTyp.Pointer()) s.inputs = append(s.inputs, &targetFuncInput{ InputIndex: inputIndex, Object: &b, @@ -194,8 +193,8 @@ func (s *FuncInjector) Inject(in *[]reflect.Value, ctx ...reflect.Value) { args := *in for _, input := range s.inputs { input.Object.Assign(ctx, func(v reflect.Value) { - // fmt.Printf("assign input index: %d for value: %v\n", - // input.InputIndex, v.String()) + // fmt.Printf("assign input index: %d for value: %v of type: %s\n", + // input.InputIndex, v.String(), v.Type().Name()) args[input.InputIndex] = v }) diff --git a/hero/di/object.go b/hero/di/object.go index 392abcc5..385162bd 100644 --- a/hero/di/object.go +++ b/hero/di/object.go @@ -101,6 +101,11 @@ func MakeReturnValue(fn reflect.Value, goodFunc TypeChecker) (func([]reflect.Val if !v.IsValid() { return zeroOutVal } + // if v.String() == "" { + // println("di/object.go: " + v.String()) + // // println("di/object.go: because it's interface{} it should be returned as: " + v.Elem().Type().String() + " and its value: " + v.Elem().Interface().(string)) + // return v.Elem() + // } return v } diff --git a/hero/di/reflect.go b/hero/di/reflect.go index 3b91ebf8..08fc7f2a 100644 --- a/hero/di/reflect.go +++ b/hero/di/reflect.go @@ -54,6 +54,7 @@ func IsZero(v reflect.Value) bool { // if can't interface, i.e return value from unexported field or method then return false return false } + zero := reflect.Zero(v.Type()) return v.Interface() == zero.Interface() } @@ -62,7 +63,10 @@ func IsZero(v reflect.Value) bool { // If "v" is a nil pointer, Indirect returns a zero Value. // If "v" is not a pointer, Indirect returns v. func IndirectValue(v reflect.Value) reflect.Value { - return reflect.Indirect(v) + if k := v.Kind(); k == reflect.Ptr { //|| k == reflect.Interface { + return v.Elem() + } + return v } // ValueOf returns the reflect.Value of "o". @@ -123,6 +127,11 @@ func equalTypes(got reflect.Type, expected reflect.Type) bool { // fmt.Printf("expected interface = %s and got to set on the arg is: %s\n", expected.String(), got.String()) return got.Implements(expected) } + + // if got.String() == "interface {}" { + // return true + // } + return false } @@ -161,7 +170,6 @@ func lookupFields(elemTyp reflect.Type, skipUnexported bool, parentIndex []int) for i, n := 0, elemTyp.NumField(); i < n; i++ { f := elemTyp.Field(i) - if IndirectType(f.Type).Kind() == reflect.Struct && !structFieldIgnored(f) { fields = append(fields, lookupFields(f.Type, skipUnexported, append(parentIndex, i))...) diff --git a/hero/handler.go b/hero/handler.go index bb427d77..f0b47044 100644 --- a/hero/handler.go +++ b/hero/handler.go @@ -5,13 +5,15 @@ import ( "reflect" "runtime" + "github.com/kataras/iris/context" "github.com/kataras/iris/hero/di" "github.com/kataras/golog" - "github.com/kataras/iris/context" ) -var contextTyp = reflect.TypeOf((*context.Context)(nil)).Elem() +var ( + contextTyp = reflect.TypeOf((*context.Context)(nil)).Elem() +) // IsContext returns true if the "inTyp" is a type of Context. func IsContext(inTyp reflect.Type) bool { @@ -70,7 +72,7 @@ func makeHandler(handler interface{}, values ...reflect.Value) (context.Handler, // is invalid when input len and values are not match // or their types are not match, we will take look at the // second statement, here we will re-try it - // using binders for path parameters: string, int, int64, bool. + // using binders for path parameters: string, int, int64, uint8, uint64, bool and so on. // We don't have access to the path, so neither to the macros here, // but in mvc. So we have to do it here. if valid = funcInjector.Retry(new(params).resolve); !valid { diff --git a/hero/param.go b/hero/param.go index 9a9f028f..6941d554 100644 --- a/hero/param.go +++ b/hero/param.go @@ -19,50 +19,8 @@ type params struct { func (p *params) resolve(index int, typ reflect.Type) (reflect.Value, bool) { currentParamIndex := p.next - v, ok := resolveParam(currentParamIndex, typ) + v, ok := context.ParamResolverByTypeAndIndex(typ, currentParamIndex) p.next = p.next + 1 return v, ok } - -func resolveParam(currentParamIndex int, typ reflect.Type) (reflect.Value, bool) { - var fn interface{} - - switch typ.Kind() { - case reflect.Int: - fn = func(ctx context.Context) int { - // the second "ok/found" check is not necessary, - // because even if the entry didn't found on that "index" - // it will return an empty entry which will return the - // default value passed from the xDefault(def) because its `ValueRaw` is nil. - entry, _ := ctx.Params().GetEntryAt(currentParamIndex) - v, _ := entry.IntDefault(0) - return v - } - case reflect.Int64: - fn = func(ctx context.Context) int64 { - entry, _ := ctx.Params().GetEntryAt(currentParamIndex) - v, _ := entry.Int64Default(0) - - return v - } - case reflect.Bool: - fn = func(ctx context.Context) bool { - entry, _ := ctx.Params().GetEntryAt(currentParamIndex) - v, _ := entry.BoolDefault(false) - return v - } - case reflect.String: - fn = func(ctx context.Context) string { - entry, _ := ctx.Params().GetEntryAt(currentParamIndex) - // print(entry.Key + " with index of: ") - // print(currentParamIndex) - // println(" and value: " + entry.String()) - return entry.String() - } - default: - return reflect.Value{}, false - } - - return reflect.ValueOf(fn), true -} diff --git a/httptest/httptest.go b/httptest/httptest.go index b37f9750..50253c53 100644 --- a/httptest/httptest.go +++ b/httptest/httptest.go @@ -84,8 +84,7 @@ func New(t *testing.T, app *iris.Application, setters ...OptionSetter) *httpexpe setter.Set(conf) } - // set the logger or disable it (default) and disable the updater (for any case). - app.Configure(iris.WithoutVersionChecker) + // set the logger or disable it (default). app.Logger().SetLevel(conf.LogLevel) if err := app.Build(); err != nil { diff --git a/iris.go b/iris.go index f84accea..5660847b 100644 --- a/iris.go +++ b/iris.go @@ -17,7 +17,6 @@ import ( // core packages, needed to build the application "github.com/kataras/iris/core/errors" "github.com/kataras/iris/core/host" - "github.com/kataras/iris/core/maintenance" "github.com/kataras/iris/core/netutil" "github.com/kataras/iris/core/router" // handlerconv conversions @@ -34,7 +33,7 @@ import ( var ( // Version is the current version number of the Iris Web Framework. - Version = maintenance.Version + Version = "11.0.0" ) // HTTP status codes as registered with IANA. @@ -58,13 +57,13 @@ const ( StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 - StatusMultipleChoices = 300 // RFC 7231, 6.4.1 - StatusMovedPermanently = 301 // RFC 7231, 6.4.2 - StatusFound = 302 // RFC 7231, 6.4.3 - StatusSeeOther = 303 // RFC 7231, 6.4.4 - StatusNotModified = 304 // RFC 7232, 4.1 - StatusUseProxy = 305 // RFC 7231, 6.4.5 - _ = 306 // RFC 7231, 6.4.6 (Unused) + StatusMultipleChoices = 300 // RFC 7231, 6.4.1 + StatusMovedPermanently = 301 // RFC 7231, 6.4.2 + StatusFound = 302 // RFC 7231, 6.4.3 + StatusSeeOther = 303 // RFC 7231, 6.4.4 + StatusNotModified = 304 // RFC 7232, 4.1 + StatusUseProxy = 305 // RFC 7231, 6.4.5 + StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7 StatusPermanentRedirect = 308 // RFC 7538, 3 @@ -87,6 +86,7 @@ const ( StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4 StatusExpectationFailed = 417 // RFC 7231, 6.5.14 StatusTeapot = 418 // RFC 7168, 2.3.3 + StatusMisdirectedRequest = 421 // RFC 7540, 9.1.2 StatusUnprocessableEntity = 422 // RFC 4918, 11.2 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 @@ -761,7 +761,7 @@ func (app *Application) Build() error { // create the request handler, the default routing handler routerHandler := router.NewDefaultHandler() - rp.Describe("router: %v", app.Router.BuildRouter(app.ContextPool, routerHandler, app.APIBuilder)) + rp.Describe("router: %v", app.Router.BuildRouter(app.ContextPool, routerHandler, app.APIBuilder, false)) // re-build of the router from outside can be done with; // app.RefreshRouter() } @@ -810,10 +810,6 @@ func (app *Application) Run(serve Runner, withOrWithout ...Configurator) error { app.Configure(withOrWithout...) app.logger.Debugf("Application: running using %d host(s)", len(app.Hosts)+1) - if !app.config.DisableVersionChecker { - go maintenance.Start() - } - // this will block until an error(unless supervisor's DeferFlow called from a Task). err := serve(app) if err != nil { diff --git a/macro/AUTHORS b/macro/AUTHORS new file mode 100644 index 00000000..04764750 --- /dev/null +++ b/macro/AUTHORS @@ -0,0 +1,4 @@ +# This is the official list of Iris Macro and Route path interpreter authors for copyright +# purposes. + +Gerasimos Maropoulos diff --git a/macro/LICENSE b/macro/LICENSE new file mode 100644 index 00000000..c73df4ce --- /dev/null +++ b/macro/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2017-2018 The Iris Macro and Route path interpreter. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Iris nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/macro/handler/handler.go b/macro/handler/handler.go new file mode 100644 index 00000000..ea36c7d5 --- /dev/null +++ b/macro/handler/handler.go @@ -0,0 +1,56 @@ +// Package handler is the highest level module of the macro package which makes use the rest of the macro package, +// it is mainly used, internally, by the router package. +package handler + +import ( + "github.com/kataras/iris/context" + "github.com/kataras/iris/macro" +) + +// CanMakeHandler reports whether a macro template needs a special macro's evaluator handler to be validated +// before procceed to the next handler(s). +// If the template does not contain any dynamic attributes and a special handler is NOT required +// then it returns false. +func CanMakeHandler(tmpl macro.Template) (needsMacroHandler bool) { + if len(tmpl.Params) == 0 { + return + } + + // check if we have params like: {name:string} or {name} or {anything:path} without else keyword or any functions used inside these params. + // 1. if we don't have, then we don't need to add a handler before the main route's handler (as I said, no performance if macro is not really used) + // 2. if we don't have any named params then we don't need a handler too. + for _, p := range tmpl.Params { + if p.CanEval() { + // if at least one needs it, then create the handler. + needsMacroHandler = true + break + } + } + + return +} + +// MakeHandler creates and returns a handler from a macro template, the handler evaluates each of the parameters if necessary at all. +// If the template does not contain any dynamic attributes and a special handler is NOT required +// then it returns a nil handler. +func MakeHandler(tmpl macro.Template) context.Handler { + if !CanMakeHandler(tmpl) { + return nil + } + + return func(ctx context.Context) { + for _, p := range tmpl.Params { + if !p.CanEval() { + continue // allow. + } + + if !p.Eval(ctx.Params().Get(p.Name), &ctx.Params().Store) { + ctx.StatusCode(p.ErrCode) + ctx.StopExecution() + return + } + } + // if all passed, just continue. + ctx.Next() + } +} diff --git a/macro/handler/handler_test.go b/macro/handler/handler_test.go new file mode 100644 index 00000000..0acc1e83 --- /dev/null +++ b/macro/handler/handler_test.go @@ -0,0 +1,41 @@ +package handler + +import ( + "testing" + + "github.com/kataras/iris/macro" +) + +func TestCanMakeHandler(t *testing.T) { + tests := []struct { + src string + needsHandler bool + }{ + {"/static/static", false}, + {"/{myparam}", false}, + {"/{myparam min(1)}", true}, + {"/{myparam else 500}", true}, + {"/{myparam else 404}", false}, + {"/{myparam:string}/static", false}, + {"/{myparam:int}", true}, + {"/static/{myparam:int}/static", true}, + {"/{myparam:path}", false}, + {"/{myparam:path min(1) else 404}", true}, + } + + availableMacros := *macro.Defaults + for i, tt := range tests { + tmpl, err := macro.Parse(tt.src, availableMacros) + if err != nil { + t.Fatalf("[%d] '%s' failed to be parsed: %v", i, tt.src, err) + } + + if got := CanMakeHandler(tmpl); got != tt.needsHandler { + if tt.needsHandler { + t.Fatalf("[%d] '%s' expected to be able to generate an evaluator handler instead of a nil one", i, tt.src) + } else { + t.Fatalf("[%d] '%s' should not need an evaluator handler", i, tt.src) + } + } + } +} diff --git a/macro/interpreter/ast/ast.go b/macro/interpreter/ast/ast.go new file mode 100644 index 00000000..a3508373 --- /dev/null +++ b/macro/interpreter/ast/ast.go @@ -0,0 +1,132 @@ +package ast + +type ( + // ParamType holds the necessary information about a parameter type for the parser to lookup for. + ParamType interface { + // The name of the parameter type. + // Indent should contain the characters for the parser. + Indent() string + } + + // MasterParamType if implemented and its `Master()` returns true then empty type param will be translated to this param type. + // Also its functions will be available to the rest of the macro param type's funcs. + // + // Only one Master is allowed. + MasterParamType interface { + ParamType + Master() bool + } + + // TrailingParamType if implemented and its `Trailing()` returns true + // then it should be declared at the end of a route path and can accept any trailing path segment as one parameter. + TrailingParamType interface { + ParamType + Trailing() bool + } + + // AliasParamType if implemeneted nad its `Alias()` returns a non-empty string + // then the param type can be written with that string literal too. + AliasParamType interface { + ParamType + Alias() string + } +) + +// IsMaster returns true if the "pt" param type is a master one. +func IsMaster(pt ParamType) bool { + p, ok := pt.(MasterParamType) + return ok && p.Master() +} + +// IsTrailing returns true if the "pt" param type is a marked as trailing, +// which should accept more than one path segment when in the end. +func IsTrailing(pt ParamType) bool { + p, ok := pt.(TrailingParamType) + return ok && p.Trailing() +} + +// HasAlias returns any alias of the "pt" param type. +// If alias is empty or not found then it returns false as its second output argument. +func HasAlias(pt ParamType) (string, bool) { + if p, ok := pt.(AliasParamType); ok { + alias := p.Alias() + return alias, len(alias) > 0 + } + + return "", false +} + +// GetMasterParamType accepts a list of ParamType and returns its master. +// If no `Master` specified: +// and len(paramTypes) > 0 then it will return the first one, +// otherwise it returns nil. +func GetMasterParamType(paramTypes ...ParamType) ParamType { + for _, pt := range paramTypes { + if IsMaster(pt) { + return pt + } + } + + if len(paramTypes) > 0 { + return paramTypes[0] + } + + return nil +} + +// LookupParamType accepts the string +// representation of a parameter type. +// Example: +// "string" +// "number" or "int" +// "long" or "int64" +// "uint8" +// "uint64" +// "boolean" or "bool" +// "alphabetical" +// "file" +// "path" +func LookupParamType(indentOrAlias string, paramTypes ...ParamType) (ParamType, bool) { + for _, pt := range paramTypes { + if pt.Indent() == indentOrAlias { + return pt, true + } + + if alias, has := HasAlias(pt); has { + if alias == indentOrAlias { + return pt, true + } + } + } + + return nil, false +} + +// ParamStatement is a struct +// which holds all the necessary information about a macro parameter. +// It holds its type (string, int, alphabetical, file, path), +// its source ({param:type}), +// its name ("param"), +// its attached functions by the user (min, max...) +// and the http error code if that parameter +// failed to be evaluated. +type ParamStatement struct { + Src string // the original unparsed source, i.e: {id:int range(1,5) else 404} + Name string // id + Type ParamType // int + Funcs []ParamFunc // range + ErrorCode int // 404 +} + +// ParamFunc holds the name of a parameter's function +// and its arguments (values) +// A param func is declared with: +// {param:int range(1,5)}, +// the range is the +// param function name +// the 1 and 5 are the two param function arguments +// range(1,5) +type ParamFunc struct { + Name string // range + Args []string // ["1","5"] +} diff --git a/core/router/macro/interpreter/lexer/lexer.go b/macro/interpreter/lexer/lexer.go similarity index 98% rename from core/router/macro/interpreter/lexer/lexer.go rename to macro/interpreter/lexer/lexer.go index 79f7111f..6a772602 100644 --- a/core/router/macro/interpreter/lexer/lexer.go +++ b/macro/interpreter/lexer/lexer.go @@ -1,7 +1,7 @@ package lexer import ( - "github.com/kataras/iris/core/router/macro/interpreter/token" + "github.com/kataras/iris/macro/interpreter/token" ) // Lexer helps us to read/scan characters of a source and resolve their token types. @@ -179,7 +179,7 @@ func (l *Lexer) skipWhitespace() { func (l *Lexer) readIdentifier() string { pos := l.pos - for isLetter(l.ch) { + for isLetter(l.ch) || isDigit(l.ch) { l.readChar() } return l.input[pos:l.pos] diff --git a/core/router/macro/interpreter/lexer/lexer_test.go b/macro/interpreter/lexer/lexer_test.go similarity index 94% rename from core/router/macro/interpreter/lexer/lexer_test.go rename to macro/interpreter/lexer/lexer_test.go index dad919f3..848731e0 100644 --- a/core/router/macro/interpreter/lexer/lexer_test.go +++ b/macro/interpreter/lexer/lexer_test.go @@ -3,7 +3,7 @@ package lexer import ( "testing" - "github.com/kataras/iris/core/router/macro/interpreter/token" + "github.com/kataras/iris/macro/interpreter/token" ) func TestNextToken(t *testing.T) { diff --git a/core/router/macro/interpreter/parser/parser.go b/macro/interpreter/parser/parser.go similarity index 70% rename from core/router/macro/interpreter/parser/parser.go rename to macro/interpreter/parser/parser.go index 8a352a73..1a0b8608 100644 --- a/core/router/macro/interpreter/parser/parser.go +++ b/macro/interpreter/parser/parser.go @@ -5,15 +5,19 @@ import ( "strconv" "strings" - "github.com/kataras/iris/core/router/macro/interpreter/ast" - "github.com/kataras/iris/core/router/macro/interpreter/lexer" - "github.com/kataras/iris/core/router/macro/interpreter/token" + "github.com/kataras/iris/macro/interpreter/ast" + "github.com/kataras/iris/macro/interpreter/lexer" + "github.com/kataras/iris/macro/interpreter/token" ) // Parse takes a route "fullpath" // and returns its param statements -// and an error on failure. -func Parse(fullpath string) ([]*ast.ParamStatement, error) { +// or an error if failed. +func Parse(fullpath string, paramTypes []ast.ParamType) ([]*ast.ParamStatement, error) { + if len(paramTypes) == 0 { + return nil, fmt.Errorf("empty parameter types") + } + pathParts := strings.SplitN(fullpath, "/", -1) p := new(ParamParser) statements := make([]*ast.ParamStatement, 0) @@ -28,14 +32,14 @@ func Parse(fullpath string) ([]*ast.ParamStatement, error) { } p.Reset(s) - stmt, err := p.Parse() + stmt, err := p.Parse(paramTypes) if err != nil { // exit on first error return nil, err } // if we have param type path but it's not the last path part - if stmt.Type == ast.ParamTypePath && i < len(pathParts)-1 { - return nil, fmt.Errorf("param type 'path' should be lived only inside the last path segment, but was inside: %s", s) + if ast.IsTrailing(stmt.Type) && i < len(pathParts)-1 { + return nil, fmt.Errorf("%s: parameter type \"%s\" should be registered to the very last of a path", s, stmt.Type.Indent()) } statements = append(statements, stmt) @@ -77,15 +81,18 @@ const ( // per-parameter. An error code can be setted via // the "else" keyword inside a route's path. DefaultParamErrorCode = 404 - // DefaultParamType when parameter type is missing use this param type, defaults to string - // and it should be remains unless earth split in two. - DefaultParamType = ast.ParamTypeString ) -func parseParamFuncArg(t token.Token) (a ast.ParamFuncArg, err error) { - if t.Type == token.INT { - return ast.ParamFuncArgToInt(t.Literal) - } +// func parseParamFuncArg(t token.Token) (a ast.ParamFuncArg, err error) { +// if t.Type == token.INT { +// return ast.ParamFuncArgToInt(t.Literal) +// } +// // act all as strings here, because of int vs int64 vs uint64 and etc. +// return t.Literal, nil +// } + +func parseParamFuncArg(t token.Token) (a string, err error) { + // act all as strings here, because of int vs int64 vs uint64 and etc. return t.Literal, nil } @@ -96,14 +103,14 @@ func (p ParamParser) Error() error { return nil } -// Parse parses the p.src and returns its param statement +// Parse parses the p.src based on the given param types and returns its param statement // and an error on failure. -func (p *ParamParser) Parse() (*ast.ParamStatement, error) { +func (p *ParamParser) Parse(paramTypes []ast.ParamType) (*ast.ParamStatement, error) { l := lexer.New(p.src) stmt := &ast.ParamStatement{ ErrorCode: DefaultParamErrorCode, - Type: DefaultParamType, + Type: ast.GetMasterParamType(paramTypes...), Src: p.src, } @@ -120,14 +127,15 @@ func (p *ParamParser) Parse() (*ast.ParamStatement, error) { switch t.Type { case token.LBRACE: - // name, alphabetical and _, param names are not allowed to contain any number. + // can accept only letter or number only. nextTok := l.NextToken() stmt.Name = nextTok.Literal case token.COLON: - // type + // type can accept both letters and numbers but not symbols ofc. nextTok := l.NextToken() - paramType := ast.LookupParamType(nextTok.Literal) - if paramType == ast.ParamTypeUnExpected { + paramType, found := ast.LookupParamType(nextTok.Literal, paramTypes...) + + if !found { p.appendErr("[%d:%d] unexpected parameter type: %s", t.Start, t.End, nextTok.Literal) } stmt.Type = paramType @@ -143,25 +151,14 @@ func (p *ParamParser) Parse() (*ast.ParamStatement, error) { argValTok := l.NextDynamicToken() // catch anything from "(" and forward, until ")", because we need to // be able to use regex expression as a macro type's func argument too. - argVal, err := parseParamFuncArg(argValTok) - if err != nil { - p.appendErr("[%d:%d] expected param func argument to be a string or number but got %s", t.Start, t.End, argValTok.Literal) - continue - } // fmt.Printf("argValTok: %#v\n", argValTok) // fmt.Printf("argVal: %#v\n", argVal) - lastParamFunc.Args = append(lastParamFunc.Args, argVal) + lastParamFunc.Args = append(lastParamFunc.Args, argValTok.Literal) case token.COMMA: argValTok := l.NextToken() - argVal, err := parseParamFuncArg(argValTok) - if err != nil { - p.appendErr("[%d:%d] expected param func argument to be a string or number type but got %s", t.Start, t.End, argValTok.Literal) - continue - } - - lastParamFunc.Args = append(lastParamFunc.Args, argVal) + lastParamFunc.Args = append(lastParamFunc.Args, argValTok.Literal) case token.RPAREN: stmt.Funcs = append(stmt.Funcs, lastParamFunc) lastParamFunc = ast.ParamFunc{} // reset diff --git a/core/router/macro/interpreter/parser/parser_test.go b/macro/interpreter/parser/parser_test.go similarity index 56% rename from core/router/macro/interpreter/parser/parser_test.go rename to macro/interpreter/parser/parser_test.go index b1ce0ad8..5424f675 100644 --- a/core/router/macro/interpreter/parser/parser_test.go +++ b/macro/interpreter/parser/parser_test.go @@ -6,9 +6,47 @@ import ( "strings" "testing" - "github.com/kataras/iris/core/router/macro/interpreter/ast" + "github.com/kataras/iris/macro/interpreter/ast" ) +type simpleParamType string + +func (pt simpleParamType) Indent() string { return string(pt) } + +type masterParamType simpleParamType + +func (pt masterParamType) Indent() string { return string(pt) } +func (pt masterParamType) Master() bool { return true } + +type wildcardParamType string + +func (pt wildcardParamType) Indent() string { return string(pt) } +func (pt wildcardParamType) Trailing() bool { return true } + +type aliasedParamType []string + +func (pt aliasedParamType) Indent() string { return string(pt[0]) } +func (pt aliasedParamType) Alias() string { return pt[1] } + +var ( + paramTypeString = masterParamType("string") + paramTypeNumber = aliasedParamType{"number", "int"} + paramTypeInt64 = aliasedParamType{"int64", "long"} + paramTypeUint8 = simpleParamType("uint8") + paramTypeUint64 = simpleParamType("uint64") + paramTypeBool = aliasedParamType{"bool", "boolean"} + paramTypeAlphabetical = simpleParamType("alphabetical") + paramTypeFile = simpleParamType("file") + paramTypePath = wildcardParamType("path") +) + +var testParamTypes = []ast.ParamType{ + paramTypeString, + paramTypeNumber, paramTypeInt64, paramTypeUint8, paramTypeUint64, + paramTypeBool, + paramTypeAlphabetical, paramTypeFile, paramTypePath, +} + func TestParseParamError(t *testing.T) { // fail illegalChar := '$' @@ -16,7 +54,7 @@ func TestParseParamError(t *testing.T) { input := "{id" + string(illegalChar) + "int range(1,5) else 404}" p := NewParamParser(input) - _, err := p.Parse() + _, err := p.Parse(testParamTypes) if err == nil { t.Fatalf("expecting not empty error on input '%s'", input) @@ -30,9 +68,9 @@ func TestParseParamError(t *testing.T) { // // success - input2 := "{id:int range(1,5) else 404}" + input2 := "{id:uint64 range(1,5) else 404}" p.Reset(input2) - _, err = p.Parse() + _, err = p.Parse(testParamTypes) if err != nil { t.Fatalf("expecting empty error on input '%s', but got: %s", input2, err.Error()) @@ -40,6 +78,16 @@ func TestParseParamError(t *testing.T) { // } +// mustLookupParamType same as `ast.LookupParamType` but it panics if "indent" does not match with a valid Param Type. +func mustLookupParamType(indent string) ast.ParamType { + pt, found := ast.LookupParamType(indent, testParamTypes...) + if !found { + panic("param type '" + indent + "' is not part of the provided param types") + } + + return pt +} + func TestParseParam(t *testing.T) { tests := []struct { valid bool @@ -49,27 +97,28 @@ func TestParseParam(t *testing.T) { ast.ParamStatement{ Src: "{id:int min(1) max(5) else 404}", Name: "id", - Type: ast.ParamTypeInt, + Type: mustLookupParamType("number"), Funcs: []ast.ParamFunc{ { Name: "min", - Args: []ast.ParamFuncArg{1}}, + Args: []string{"1"}}, { Name: "max", - Args: []ast.ParamFuncArg{5}}, + Args: []string{"5"}}, }, ErrorCode: 404, }}, // 0 {true, ast.ParamStatement{ - Src: "{id:int range(1,5)}", + // test alias of int. + Src: "{id:number range(1,5)}", Name: "id", - Type: ast.ParamTypeInt, + Type: mustLookupParamType("number"), Funcs: []ast.ParamFunc{ { Name: "range", - Args: []ast.ParamFuncArg{1, 5}}, + Args: []string{"1", "5"}}, }, ErrorCode: 404, }}, // 1 @@ -77,11 +126,11 @@ func TestParseParam(t *testing.T) { ast.ParamStatement{ Src: "{file:path contains(.)}", Name: "file", - Type: ast.ParamTypePath, + Type: mustLookupParamType("path"), Funcs: []ast.ParamFunc{ { Name: "contains", - Args: []ast.ParamFuncArg{"."}}, + Args: []string{"."}}, }, ErrorCode: 404, }}, // 2 @@ -89,35 +138,35 @@ func TestParseParam(t *testing.T) { ast.ParamStatement{ Src: "{username:alphabetical}", Name: "username", - Type: ast.ParamTypeAlphabetical, + Type: mustLookupParamType("alphabetical"), ErrorCode: 404, }}, // 3 {true, ast.ParamStatement{ Src: "{myparam}", Name: "myparam", - Type: ast.ParamTypeString, + Type: mustLookupParamType("string"), ErrorCode: 404, }}, // 4 {false, ast.ParamStatement{ Src: "{myparam_:thisianunexpected}", Name: "myparam_", - Type: ast.ParamTypeUnExpected, + Type: nil, ErrorCode: 404, }}, // 5 - {false, // false because it will give an error of unexpeced token type with value 2 + {true, ast.ParamStatement{ Src: "{myparam2}", - Name: "myparam", // expected "myparam" because we don't allow integers to the parameter names. - Type: ast.ParamTypeString, + Name: "myparam2", // we now allow integers to the parameter names. + Type: ast.GetMasterParamType(testParamTypes...), ErrorCode: 404, }}, // 6 {true, ast.ParamStatement{ Src: "{id:int even()}", // test param funcs without any arguments (LPAREN peek for RPAREN) Name: "id", - Type: ast.ParamTypeInt, + Type: mustLookupParamType("number"), Funcs: []ast.ParamFunc{ { Name: "even"}, @@ -126,25 +175,46 @@ func TestParseParam(t *testing.T) { }}, // 7 {true, ast.ParamStatement{ - Src: "{id:long else 404}", + Src: "{id:int64 else 404}", Name: "id", - Type: ast.ParamTypeLong, + Type: mustLookupParamType("int64"), ErrorCode: 404, }}, // 8 {true, ast.ParamStatement{ - Src: "{has:boolean else 404}", - Name: "has", - Type: ast.ParamTypeBoolean, + Src: "{id:long else 404}", // backwards-compatible test. + Name: "id", + Type: mustLookupParamType("int64"), ErrorCode: 404, }}, // 9 + {true, + ast.ParamStatement{ + Src: "{id:long else 404}", + Name: "id", + Type: mustLookupParamType("int64"), // backwards-compatible test of LookupParamType. + ErrorCode: 404, + }}, // 10 + {true, + ast.ParamStatement{ + Src: "{has:bool else 404}", + Name: "has", + Type: mustLookupParamType("bool"), + ErrorCode: 404, + }}, // 11 + {true, + ast.ParamStatement{ + Src: "{has:boolean else 404}", // backwards-compatible test. + Name: "has", + Type: mustLookupParamType("bool"), + ErrorCode: 404, + }}, // 12 } p := new(ParamParser) for i, tt := range tests { p.Reset(tt.expectedStatement.Src) - resultStmt, err := p.Parse() + resultStmt, err := p.Parse(testParamTypes) if tt.valid && err != nil { t.Fatalf("tests[%d] - error %s", i, err.Error()) @@ -171,27 +241,27 @@ func TestParse(t *testing.T) { []ast.ParamStatement{{ Src: "{id:int min(1) max(5) else 404}", Name: "id", - Type: ast.ParamTypeInt, + Type: paramTypeNumber, Funcs: []ast.ParamFunc{ { Name: "min", - Args: []ast.ParamFuncArg{1}}, + Args: []string{"1"}}, { Name: "max", - Args: []ast.ParamFuncArg{5}}, + Args: []string{"5"}}, }, ErrorCode: 404, }, }}, // 0 - {"/admin/{id:int range(1,5)}", true, + {"/admin/{id:uint64 range(1,5)}", true, []ast.ParamStatement{{ - Src: "{id:int range(1,5)}", + Src: "{id:uint64 range(1,5)}", Name: "id", - Type: ast.ParamTypeInt, + Type: paramTypeUint64, Funcs: []ast.ParamFunc{ { Name: "range", - Args: []ast.ParamFuncArg{1, 5}}, + Args: []string{"1", "5"}}, }, ErrorCode: 404, }, @@ -200,11 +270,11 @@ func TestParse(t *testing.T) { []ast.ParamStatement{{ Src: "{file:path contains(.)}", Name: "file", - Type: ast.ParamTypePath, + Type: paramTypePath, Funcs: []ast.ParamFunc{ { Name: "contains", - Args: []ast.ParamFuncArg{"."}}, + Args: []string{"."}}, }, ErrorCode: 404, }, @@ -213,7 +283,7 @@ func TestParse(t *testing.T) { []ast.ParamStatement{{ Src: "{username:alphabetical}", Name: "username", - Type: ast.ParamTypeAlphabetical, + Type: paramTypeAlphabetical, ErrorCode: 404, }, }}, // 3 @@ -221,7 +291,7 @@ func TestParse(t *testing.T) { []ast.ParamStatement{{ Src: "{myparam}", Name: "myparam", - Type: ast.ParamTypeString, + Type: paramTypeString, ErrorCode: 404, }, }}, // 4 @@ -229,15 +299,15 @@ func TestParse(t *testing.T) { []ast.ParamStatement{{ Src: "{myparam_:thisianunexpected}", Name: "myparam_", - Type: ast.ParamTypeUnExpected, + Type: nil, ErrorCode: 404, }, }}, // 5 - {"/p2/{myparam2}", false, // false because it will give an error of unexpeced token type with value 2 + {"/p2/{myparam2}", true, []ast.ParamStatement{{ Src: "{myparam2}", - Name: "myparam", // expected "myparam" because we don't allow integers to the parameter names. - Type: ast.ParamTypeString, + Name: "myparam2", // we now allow integers to the parameter names. + Type: paramTypeString, ErrorCode: 404, }, }}, // 6 @@ -245,13 +315,13 @@ func TestParse(t *testing.T) { []ast.ParamStatement{{ Src: "{file:path}", Name: "file", - Type: ast.ParamTypePath, + Type: paramTypePath, ErrorCode: 404, }, }}, // 7 } for i, tt := range tests { - statements, err := Parse(tt.path) + statements, err := Parse(tt.path, testParamTypes) if tt.valid && err != nil { t.Fatalf("tests[%d] - error %s", i, err.Error()) diff --git a/core/router/macro/interpreter/token/token.go b/macro/interpreter/token/token.go similarity index 96% rename from core/router/macro/interpreter/token/token.go rename to macro/interpreter/token/token.go index 620ad641..b964db1d 100644 --- a/core/router/macro/interpreter/token/token.go +++ b/macro/interpreter/token/token.go @@ -13,7 +13,7 @@ type Token struct { // /about/{fullname:alphabetical} // /profile/{anySpecialName:string} -// {id:int range(1,5) else 404} +// {id:uint64 range(1,5) else 404} // /admin/{id:int eq(1) else 402} // /file/{filepath:file else 405} const ( diff --git a/macro/macro.go b/macro/macro.go new file mode 100644 index 00000000..c4c55704 --- /dev/null +++ b/macro/macro.go @@ -0,0 +1,344 @@ +package macro + +import ( + "fmt" + "reflect" + "regexp" + "strconv" + "strings" + "unicode" +) + +type ( + // ParamEvaluator is the signature for param type evaluator. + // It accepts the param's value as string and returns + // the value (which its type is used for the input argument of the parameter functions, if any) + // and a true value for passed, otherwise nil and false should be returned. + ParamEvaluator func(paramValue string) (interface{}, bool) +) + +var goodEvaluatorFuncs = []reflect.Type{ + reflect.TypeOf(func(string) (interface{}, bool) { return nil, false }), + reflect.TypeOf(ParamEvaluator(func(string) (interface{}, bool) { return nil, false })), +} + +func goodParamFunc(typ reflect.Type) bool { + if typ.Kind() == reflect.Func { // it should be a func which returns a func (see below check). + if typ.NumOut() == 1 { + typOut := typ.Out(0) + if typOut.Kind() != reflect.Func { + return false + } + + if typOut.NumOut() == 2 { // if it's a type of EvaluatorFunc, used for param evaluator. + for _, fType := range goodEvaluatorFuncs { + if typOut == fType { + return true + } + } + return false + } + + if typOut.NumIn() == 1 && typOut.NumOut() == 1 { // if it's a type of func(paramValue [int,string...]) bool, used for param funcs. + return typOut.Out(0).Kind() == reflect.Bool + } + } + } + + return false +} + +// Regexp accepts a regexp "expr" expression +// and returns its MatchString. +// The regexp is compiled before return. +// +// Returns a not-nil error on regexp compile failure. +func Regexp(expr string) (func(string) bool, error) { + if expr == "" { + return nil, fmt.Errorf("empty regex expression") + } + + // add the last $ if missing (and not wildcard(?)) + if i := expr[len(expr)-1]; i != '$' && i != '*' { + expr += "$" + } + + r, err := regexp.Compile(expr) + if err != nil { + return nil, err + } + + return r.MatchString, nil +} + +// MustRegexp same as Regexp +// but it panics on the "expr" parse failure. +func MustRegexp(expr string) func(string) bool { + r, err := Regexp(expr) + if err != nil { + panic(err) + } + return r +} + +// goodParamFuncName reports whether the function name is a valid identifier. +func goodParamFuncName(name string) bool { + if name == "" { + return false + } + // valid names are only letters and _ + for _, r := range name { + switch { + case r == '_': + case !unicode.IsLetter(r): + return false + } + } + return true +} + +// the convertBuilderFunc return value is generating at boot time. +// convertFunc converts an interface to a valid full param function. +func convertBuilderFunc(fn interface{}) ParamFuncBuilder { + + typFn := reflect.TypeOf(fn) + if !goodParamFunc(typFn) { + return nil + } + + numFields := typFn.NumIn() + + return func(args []string) reflect.Value { + if len(args) != numFields { + // no variadics support, for now. + panic("args should be the same len as numFields") + } + var argValues []reflect.Value + for i := 0; i < numFields; i++ { + field := typFn.In(i) + arg := args[i] + + // try to convert the string literal as we get it from the parser. + var ( + val interface{} + + panicIfErr = func(err error) { + if err != nil { + panic(fmt.Sprintf("on field index: %d: %v", i, err)) + } + } + ) + + // try to get the value based on the expected type. + switch field.Kind() { + case reflect.Int: + v, err := strconv.Atoi(arg) + panicIfErr(err) + val = v + case reflect.Int8: + v, err := strconv.ParseInt(arg, 10, 8) + panicIfErr(err) + val = int8(v) + case reflect.Int16: + v, err := strconv.ParseInt(arg, 10, 16) + panicIfErr(err) + val = int16(v) + case reflect.Int32: + v, err := strconv.ParseInt(arg, 10, 32) + panicIfErr(err) + val = int32(v) + case reflect.Int64: + v, err := strconv.ParseInt(arg, 10, 64) + panicIfErr(err) + val = v + case reflect.Uint: + v, err := strconv.ParseUint(arg, 10, strconv.IntSize) + panicIfErr(err) + val = uint(v) + case reflect.Uint8: + v, err := strconv.ParseUint(arg, 10, 8) + panicIfErr(err) + val = uint8(v) + case reflect.Uint16: + v, err := strconv.ParseUint(arg, 10, 16) + panicIfErr(err) + val = uint16(v) + case reflect.Uint32: + v, err := strconv.ParseUint(arg, 10, 32) + panicIfErr(err) + val = uint32(v) + case reflect.Uint64: + v, err := strconv.ParseUint(arg, 10, 64) + panicIfErr(err) + val = v + case reflect.Float32: + v, err := strconv.ParseFloat(arg, 32) + panicIfErr(err) + val = float32(v) + case reflect.Float64: + v, err := strconv.ParseFloat(arg, 64) + panicIfErr(err) + val = v + case reflect.Bool: + v, err := strconv.ParseBool(arg) + panicIfErr(err) + val = v + case reflect.Slice: + if len(arg) > 1 { + if arg[0] == '[' && arg[len(arg)-1] == ']' { + // it is a single argument but as slice. + val = strings.Split(arg[1:len(arg)-1], ",") // only string slices. + } + } + + default: + val = arg + } + + argValue := reflect.ValueOf(val) + if expected, got := field.Kind(), argValue.Kind(); expected != got { + panic(fmt.Sprintf("func's input arguments should have the same type: [%d] expected %s but got %s", i, expected, got)) + } + + argValues = append(argValues, argValue) + } + + evalFn := reflect.ValueOf(fn).Call(argValues)[0] + + // var evaluator EvaluatorFunc + // // check for typed and not typed + // if _v, ok := evalFn.(EvaluatorFunc); ok { + // evaluator = _v + // } else if _v, ok = evalFn.(func(string) bool); ok { + // evaluator = _v + // } + // return func(paramValue interface{}) bool { + // return evaluator(paramValue) + // } + return evalFn + } +} + +type ( + // Macro represents the parsed macro, + // which holds + // the evaluator (param type's evaluator + param functions evaluators) + // and its param functions. + // + // Any type contains its own macro + // instance, so an String type + // contains its type evaluator + // which is the "Evaluator" field + // and it can register param functions + // to that macro which maps to a parameter type. + Macro struct { + indent string + alias string + master bool + trailing bool + + Evaluator ParamEvaluator + funcs []ParamFunc + } + + // ParamFuncBuilder is a func + // which accepts a param function's arguments (values) + // and returns a function as value, its job + // is to make the macros to be registered + // by user at the most generic possible way. + ParamFuncBuilder func([]string) reflect.Value // the func() bool + + // ParamFunc represents the parsed + // parameter function, it holds + // the parameter's name + // and the function which will build + // the evaluator func. + ParamFunc struct { + Name string + Func ParamFuncBuilder + } +) + +// NewMacro creates and returns a Macro that can be used as a registry for +// a new customized parameter type and its functions. +func NewMacro(indent, alias string, master, trailing bool, evaluator ParamEvaluator) *Macro { + return &Macro{ + indent: indent, + alias: alias, + master: master, + trailing: trailing, + + Evaluator: evaluator, + } +} + +// Indent returns the name of the parameter type. +func (m *Macro) Indent() string { + return m.indent +} + +// Alias returns the alias of the parameter type, if any. +func (m *Macro) Alias() string { + return m.alias +} + +// Master returns true if that macro's parameter type is the +// default one if not :type is followed by a parameter type inside the route path. +func (m *Macro) Master() bool { + return m.master +} + +// Trailing returns true if that macro's parameter type +// is wildcard and can accept one or more path segments as one parameter value. +// A wildcard should be registered in the last path segment only. +func (m *Macro) Trailing() bool { + return m.trailing +} + +// func (m *Macro) SetParamResolver(fn func(memstore.Entry) interface{}) *Macro { +// m.ParamResolver = fn +// return m +// } + +// RegisterFunc registers a parameter function +// to that macro. +// Accepts the func name ("range") +// and the function body, which should return an EvaluatorFunc +// a bool (it will be converted to EvaluatorFunc later on), +// i.e RegisterFunc("min", func(minValue int) func(paramValue string) bool){}) +func (m *Macro) RegisterFunc(funcName string, fn interface{}) *Macro { + fullFn := convertBuilderFunc(fn) + m.registerFunc(funcName, fullFn) + + return m +} + +func (m *Macro) registerFunc(funcName string, fullFn ParamFuncBuilder) { + if !goodParamFuncName(funcName) { + return + } + + for _, fn := range m.funcs { + if fn.Name == funcName { + fn.Func = fullFn + return + } + } + + m.funcs = append(m.funcs, ParamFunc{ + Name: funcName, + Func: fullFn, + }) +} + +func (m *Macro) getFunc(funcName string) ParamFuncBuilder { + for _, fn := range m.funcs { + if fn.Name == funcName { + if fn.Func == nil { + continue + } + return fn.Func + } + } + return nil +} diff --git a/macro/macro_test.go b/macro/macro_test.go new file mode 100644 index 00000000..ff25c817 --- /dev/null +++ b/macro/macro_test.go @@ -0,0 +1,453 @@ +package macro + +import ( + "reflect" + "strconv" + "testing" +) + +// Most important tests to look: +// ../parser/parser_test.go +// ../lexer/lexer_test.go + +func TestGoodParamFunc(t *testing.T) { + good1 := func(min int, max int) func(string) bool { + return func(paramValue string) bool { + return true + } + } + + good2 := func(min uint64, max uint64) func(string) bool { + return func(paramValue string) bool { + return true + } + } + + notgood1 := func(min int, max int) bool { + return false + } + + if !goodParamFunc(reflect.TypeOf(good1)) { + t.Fatalf("expected good1 func to be good but it's not") + } + + if !goodParamFunc(reflect.TypeOf(good2)) { + t.Fatalf("expected good2 func to be good but it's not") + } + + if goodParamFunc(reflect.TypeOf(notgood1)) { + t.Fatalf("expected notgood1 func to be the worst") + } +} + +func TestGoodParamFuncName(t *testing.T) { + tests := []struct { + name string + good bool + }{ + {"range", true}, + {"_range", true}, + {"range_", true}, + {"r_ange", true}, + // numbers or other symbols are invalid. + {"range1", false}, + {"2range", false}, + {"r@nge", false}, + {"rang3", false}, + } + for i, tt := range tests { + isGood := goodParamFuncName(tt.name) + if tt.good && !isGood { + t.Fatalf("tests[%d] - expecting valid name but got invalid for name %s", i, tt.name) + } else if !tt.good && isGood { + t.Fatalf("tests[%d] - expecting invalid name but got valid for name %s", i, tt.name) + } + } +} + +func testEvaluatorRaw(t *testing.T, macroEvaluator *Macro, input string, expectedType reflect.Kind, pass bool, i int) { + if macroEvaluator.Evaluator == nil && pass { + return // if not evaluator defined then it should allow everything. + } + value, passed := macroEvaluator.Evaluator(input) + if pass != passed { + t.Fatalf("%s - tests[%d] - expecting[pass] %v but got %v", t.Name(), i, pass, passed) + } + + if !passed { + return + } + + if value == nil && expectedType != reflect.Invalid { + t.Fatalf("%s - tests[%d] - expecting[value] to not be nil", t.Name(), i) + } + + if v := reflect.ValueOf(value); v.Kind() != expectedType { + t.Fatalf("%s - tests[%d] - expecting[value.Kind] %v but got %v", t.Name(), i, expectedType, v.Kind()) + } +} + +func TestStringEvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {true, "astring"}, // 0 + {true, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {true, "main.css"}, // 3 + {true, "/assets/main.css"}, // 4 + // false never + } // 0 + + for i, tt := range tests { + testEvaluatorRaw(t, String, tt.input, reflect.String, tt.pass, i) + } +} + +func TestIntEvaluatorRaw(t *testing.T) { + x64 := strconv.IntSize == 64 + + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {x64, "9223372036854775807" /* max int64 */}, // 3 + {x64, "-9223372036854775808" /* min int64 */}, // 4 + {false, "-18446744073709553213213213213213121615"}, // 5 + {false, "42 18446744073709551615"}, // 6 + {false, "--42"}, // 7 + {false, "+42"}, // 8 + {false, "main.css"}, // 9 + {false, "/assets/main.css"}, // 10 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Int, tt.input, reflect.Int, tt.pass, i) + } +} + +func TestInt8EvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {false, "32321"}, // 2 + {true, "127" /* max int8 */}, // 3 + {true, "-128" /* min int8 */}, // 4 + {false, "128"}, // 5 + {false, "-129"}, // 6 + {false, "-18446744073709553213213213213213121615"}, // 7 + {false, "42 18446744073709551615"}, // 8 + {false, "--42"}, // 9 + {false, "+42"}, // 10 + {false, "main.css"}, // 11 + {false, "/assets/main.css"}, // 12 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Int8, tt.input, reflect.Int8, tt.pass, i) + } +} + +func TestInt16EvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {true, "32767" /* max int16 */}, // 3 + {true, "-32768" /* min int16 */}, // 4 + {false, "-32769"}, // 5 + {false, "32768"}, // 6 + {false, "-18446744073709553213213213213213121615"}, // 7 + {false, "42 18446744073709551615"}, // 8 + {false, "--42"}, // 9 + {false, "+42"}, // 10 + {false, "main.css"}, // 11 + {false, "/assets/main.css"}, // 12 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Int16, tt.input, reflect.Int16, tt.pass, i) + } +} + +func TestInt32EvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {true, "1"}, // 3 + {true, "42"}, // 4 + {true, "2147483647" /* max int32 */}, // 5 + {true, "-2147483648" /* min int32 */}, // 6 + {false, "-2147483649"}, // 7 + {false, "2147483648"}, // 8 + {false, "-18446744073709553213213213213213121615"}, // 9 + {false, "42 18446744073709551615"}, // 10 + {false, "--42"}, // 11 + {false, "+42"}, // 12 + {false, "main.css"}, // 13 + {false, "/assets/main.css"}, // 14 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Int32, tt.input, reflect.Int32, tt.pass, i) + } +} + +func TestInt64EvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {false, "18446744073709551615"}, // 2 + {false, "92233720368547758079223372036854775807"}, // 3 + {false, "9223372036854775808 9223372036854775808"}, // 4 + {false, "main.css"}, // 5 + {false, "/assets/main.css"}, // 6 + {true, "9223372036854775807"}, // 7 + {true, "-9223372036854775808"}, // 8 + {true, "-0"}, // 9 + {true, "1"}, // 10 + {true, "-042"}, // 11 + {true, "142"}, // 12 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Int64, tt.input, reflect.Int64, tt.pass, i) + } +} + +func TestUintEvaluatorRaw(t *testing.T) { + x64 := strconv.IntSize == 64 + + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {true, "1"}, // 3 + {true, "42"}, // 4 + {x64, "18446744073709551615" /* max uint64 */}, // 5 + {true, "4294967295" /* max uint32 */}, // 6 + {false, "-2147483649"}, // 7 + {true, "2147483648"}, // 8 + {false, "-18446744073709553213213213213213121615"}, // 9 + {false, "42 18446744073709551615"}, // 10 + {false, "--42"}, // 11 + {false, "+42"}, // 12 + {false, "main.css"}, // 13 + {false, "/assets/main.css"}, // 14 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Uint, tt.input, reflect.Uint, tt.pass, i) + } +} + +func TestUint8EvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {false, "-9223372036854775808"}, // 2 + {false, "main.css"}, // 3 + {false, "/assets/main.css"}, // 4 + {false, "92233720368547758079223372036854775807"}, // 5 + {false, "9223372036854775808 9223372036854775808"}, // 6 + {false, "-1"}, // 7 + {false, "-0"}, // 8 + {false, "+1"}, // 9 + {false, "18446744073709551615"}, // 10 + {false, "9223372036854775807"}, // 11 + {false, "021"}, // 12 - no leading zeroes are allowed. + {false, "300"}, // 13 + {true, "0"}, // 14 + {true, "255"}, // 15 + {true, "21"}, // 16 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Uint8, tt.input, reflect.Uint8, tt.pass, i) + } +} + +func TestUint16EvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {true, "65535" /* max uint16 */}, // 3 + {true, "0" /* min uint16 */}, // 4 + {false, "-32769"}, // 5 + {true, "32768"}, // 6 + {false, "-18446744073709553213213213213213121615"}, // 7 + {false, "42 18446744073709551615"}, // 8 + {false, "--42"}, // 9 + {false, "+42"}, // 10 + {false, "main.css"}, // 11 + {false, "/assets/main.css"}, // 12 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Uint16, tt.input, reflect.Uint16, tt.pass, i) + } +} + +func TestUint32EvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {true, "1"}, // 3 + {true, "42"}, // 4 + {true, "4294967295" /* max uint32*/}, // 5 + {true, "0" /* min uint32 */}, // 6 + {false, "-2147483649"}, // 7 + {true, "2147483648"}, // 8 + {false, "-18446744073709553213213213213213121615"}, // 9 + {false, "42 18446744073709551615"}, // 10 + {false, "--42"}, // 11 + {false, "+42"}, // 12 + {false, "main.css"}, // 13 + {false, "/assets/main.css"}, // 14 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Uint32, tt.input, reflect.Uint32, tt.pass, i) + } +} + +func TestUint64EvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {false, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {false, "-9223372036854775808"}, // 2 + {false, "main.css"}, // 3 + {false, "/assets/main.css"}, // 4 + {false, "92233720368547758079223372036854775807"}, // 5 + {false, "9223372036854775808 9223372036854775808"}, // 6 + {false, "-1"}, // 7 + {false, "-0"}, // 8 + {false, "+1"}, // 9 + {true, "18446744073709551615"}, // 10 + {true, "9223372036854775807"}, // 11 + {true, "0"}, // 12 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Uint64, tt.input, reflect.Uint64, tt.pass, i) + } +} + +func TestAlphabeticalEvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {true, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {false, "32321"}, // 2 + {false, "main.css"}, // 3 + {false, "/assets/main.css"}, // 4 + } + + for i, tt := range tests { + testEvaluatorRaw(t, Alphabetical, tt.input, reflect.String, tt.pass, i) + } +} + +func TestFileEvaluatorRaw(t *testing.T) { + tests := []struct { + pass bool + input string + }{ + {true, "astring"}, // 0 + {false, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {true, "main.css"}, // 3 + {false, "/assets/main.css"}, // 4 + } + + for i, tt := range tests { + testEvaluatorRaw(t, File, tt.input, reflect.String, tt.pass, i) + } +} + +func TestPathEvaluatorRaw(t *testing.T) { + pathTests := []struct { + pass bool + input string + }{ + {true, "astring"}, // 0 + {true, "astringwith_numb3rS_and_symbol$"}, // 1 + {true, "32321"}, // 2 + {true, "main.css"}, // 3 + {true, "/assets/main.css"}, // 4 + {true, "disk/assets/main.css"}, // 5 + } + + for i, tt := range pathTests { + testEvaluatorRaw(t, Path, tt.input, reflect.String, tt.pass, i) + } +} + +func TestConvertBuilderFunc(t *testing.T) { + fn := func(min uint64, slice []string) func(string) bool { + return func(paramValue string) bool { + if expected, got := "ok", paramValue; expected != got { + t.Fatalf("paramValue is not the expected one: %s vs %s", expected, got) + } + + if expected, got := uint64(1), min; expected != got { + t.Fatalf("min argument is not the expected one: %d vs %d", expected, got) + } + + if expected, got := []string{"name1", "name2"}, slice; len(expected) == len(got) { + if expected, got := "name1", slice[0]; expected != got { + t.Fatalf("slice argument[%d] does not contain the expected value: %s vs %s", 0, expected, got) + } + + if expected, got := "name2", slice[1]; expected != got { + t.Fatalf("slice argument[%d] does not contain the expected value: %s vs %s", 1, expected, got) + } + } else { + t.Fatalf("slice argument is not the expected one, the length is difference: %d vs %d", len(expected), len(got)) + } + + return true + } + } + + evalFunc := convertBuilderFunc(fn) + if !evalFunc([]string{"1", "[name1,name2]"}).Call([]reflect.Value{reflect.ValueOf("ok")})[0].Interface().(bool) { + t.Fatalf("failed, it should fail already") + } +} diff --git a/macro/macros.go b/macro/macros.go new file mode 100644 index 00000000..4c6f6416 --- /dev/null +++ b/macro/macros.go @@ -0,0 +1,550 @@ +package macro + +import ( + "strconv" + "strings" + + "github.com/kataras/iris/macro/interpreter/ast" +) + +var ( + // String type + // Allows anything (single path segment, as everything except the `Path`). + // Its functions can be used by the rest of the macros and param types whenever not available function by name is used. + // Because of its "master" boolean value to true (third parameter). + String = NewMacro("string", "", true, false, nil). + RegisterFunc("regexp", MustRegexp). + // checks if param value starts with the 'prefix' arg + RegisterFunc("prefix", func(prefix string) func(string) bool { + return func(paramValue string) bool { + return strings.HasPrefix(paramValue, prefix) + } + }). + // checks if param value ends with the 'suffix' arg + RegisterFunc("suffix", func(suffix string) func(string) bool { + return func(paramValue string) bool { + return strings.HasSuffix(paramValue, suffix) + } + }). + // checks if param value contains the 's' arg + RegisterFunc("contains", func(s string) func(string) bool { + return func(paramValue string) bool { + return strings.Contains(paramValue, s) + } + }). + // checks if param value's length is at least 'min' + RegisterFunc("min", func(min int) func(string) bool { + return func(paramValue string) bool { + return len(paramValue) >= min + } + }). + // checks if param value's length is not bigger than 'max' + RegisterFunc("max", func(max int) func(string) bool { + return func(paramValue string) bool { + return max >= len(paramValue) + } + }) + + simpleNumberEval = MustRegexp("^-?[0-9]+$") + // Int or number type + // both positive and negative numbers, actual value can be min-max int64 or min-max int32 depends on the arch. + // If x64: -9223372036854775808 to 9223372036854775807. + // If x32: -2147483648 to 2147483647 and etc.. + Int = NewMacro("int", "number", false, false, func(paramValue string) (interface{}, bool) { + if !simpleNumberEval(paramValue) { + return nil, false + } + + v, err := strconv.Atoi(paramValue) + if err != nil { + return nil, false + } + + return v, true + }). + // checks if the param value's int representation is + // bigger or equal than 'min' + RegisterFunc("min", func(min int) func(int) bool { + return func(paramValue int) bool { + return paramValue >= min + } + }). + // checks if the param value's int representation is + // smaller or equal than 'max'. + RegisterFunc("max", func(max int) func(int) bool { + return func(paramValue int) bool { + return paramValue <= max + } + }). + // checks if the param value's int representation is + // between min and max, including 'min' and 'max'. + RegisterFunc("range", func(min, max int) func(int) bool { + return func(paramValue int) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Int8 type + // -128 to 127. + Int8 = NewMacro("int8", "", false, false, func(paramValue string) (interface{}, bool) { + if !simpleNumberEval(paramValue) { + return nil, false + } + + v, err := strconv.ParseInt(paramValue, 10, 8) + if err != nil { + return nil, false + } + return int8(v), true + }). + RegisterFunc("min", func(min int8) func(int8) bool { + return func(paramValue int8) bool { + return paramValue >= min + } + }). + RegisterFunc("max", func(max int8) func(int8) bool { + return func(paramValue int8) bool { + return paramValue <= max + } + }). + RegisterFunc("range", func(min, max int8) func(int8) bool { + return func(paramValue int8) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Int16 type + // -32768 to 32767. + Int16 = NewMacro("int16", "", false, false, func(paramValue string) (interface{}, bool) { + if !simpleNumberEval(paramValue) { + return nil, false + } + + v, err := strconv.ParseInt(paramValue, 10, 16) + if err != nil { + return nil, false + } + return int16(v), true + }). + RegisterFunc("min", func(min int16) func(int16) bool { + return func(paramValue int16) bool { + return paramValue >= min + } + }). + RegisterFunc("max", func(max int16) func(int16) bool { + return func(paramValue int16) bool { + return paramValue <= max + } + }). + RegisterFunc("range", func(min, max int16) func(int16) bool { + return func(paramValue int16) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Int32 type + // -2147483648 to 2147483647. + Int32 = NewMacro("int32", "", false, false, func(paramValue string) (interface{}, bool) { + if !simpleNumberEval(paramValue) { + return nil, false + } + + v, err := strconv.ParseInt(paramValue, 10, 32) + if err != nil { + return nil, false + } + return int32(v), true + }). + RegisterFunc("min", func(min int32) func(int32) bool { + return func(paramValue int32) bool { + return paramValue >= min + } + }). + RegisterFunc("max", func(max int32) func(int32) bool { + return func(paramValue int32) bool { + return paramValue <= max + } + }). + RegisterFunc("range", func(min, max int32) func(int32) bool { + return func(paramValue int32) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Int64 as int64 type + // -9223372036854775808 to 9223372036854775807. + Int64 = NewMacro("int64", "long", false, false, func(paramValue string) (interface{}, bool) { + if !simpleNumberEval(paramValue) { + return nil, false + } + + v, err := strconv.ParseInt(paramValue, 10, 64) + if err != nil { // if err == strconv.ErrRange... + return nil, false + } + return v, true + }). + // checks if the param value's int64 representation is + // bigger or equal than 'min'. + RegisterFunc("min", func(min int64) func(int64) bool { + return func(paramValue int64) bool { + return paramValue >= min + } + }). + // checks if the param value's int64 representation is + // smaller or equal than 'max'. + RegisterFunc("max", func(max int64) func(int64) bool { + return func(paramValue int64) bool { + return paramValue <= max + } + }). + // checks if the param value's int64 representation is + // between min and max, including 'min' and 'max'. + RegisterFunc("range", func(min, max int64) func(int64) bool { + return func(paramValue int64) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Uint as uint type + // actual value can be min-max uint64 or min-max uint32 depends on the arch. + // If x64: 0 to 18446744073709551615. + // If x32: 0 to 4294967295 and etc. + Uint = NewMacro("uint", "", false, false, func(paramValue string) (interface{}, bool) { + v, err := strconv.ParseUint(paramValue, 10, strconv.IntSize) // 32,64... + if err != nil { + return nil, false + } + return uint(v), true + }). + // checks if the param value's int representation is + // bigger or equal than 'min' + RegisterFunc("min", func(min uint) func(uint) bool { + return func(paramValue uint) bool { + return paramValue >= min + } + }). + // checks if the param value's int representation is + // smaller or equal than 'max'. + RegisterFunc("max", func(max uint) func(uint) bool { + return func(paramValue uint) bool { + return paramValue <= max + } + }). + // checks if the param value's int representation is + // between min and max, including 'min' and 'max'. + RegisterFunc("range", func(min, max uint) func(uint) bool { + return func(paramValue uint) bool { + return !(paramValue < min || paramValue > max) + } + }) + + uint8Eval = MustRegexp("^([0-9]|[1-8][0-9]|9[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$") + // Uint8 as uint8 type + // 0 to 255. + Uint8 = NewMacro("uint8", "", false, false, func(paramValue string) (interface{}, bool) { + if !uint8Eval(paramValue) { + return nil, false + } + + v, err := strconv.ParseUint(paramValue, 10, 8) + if err != nil { + return nil, false + } + return uint8(v), true + }). + // checks if the param value's uint8 representation is + // bigger or equal than 'min'. + RegisterFunc("min", func(min uint8) func(uint8) bool { + return func(paramValue uint8) bool { + return paramValue >= min + } + }). + // checks if the param value's uint8 representation is + // smaller or equal than 'max'. + RegisterFunc("max", func(max uint8) func(uint8) bool { + return func(paramValue uint8) bool { + return paramValue <= max + } + }). + // checks if the param value's uint8 representation is + // between min and max, including 'min' and 'max'. + RegisterFunc("range", func(min, max uint8) func(uint8) bool { + return func(paramValue uint8) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Uint16 as uint16 type + // 0 to 65535. + Uint16 = NewMacro("uint16", "", false, false, func(paramValue string) (interface{}, bool) { + v, err := strconv.ParseUint(paramValue, 10, 16) + if err != nil { + return nil, false + } + return uint16(v), true + }). + RegisterFunc("min", func(min uint16) func(uint16) bool { + return func(paramValue uint16) bool { + return paramValue >= min + } + }). + RegisterFunc("max", func(max uint16) func(uint16) bool { + return func(paramValue uint16) bool { + return paramValue <= max + } + }). + RegisterFunc("range", func(min, max uint16) func(uint16) bool { + return func(paramValue uint16) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Uint32 as uint32 type + // 0 to 4294967295. + Uint32 = NewMacro("uint32", "", false, false, func(paramValue string) (interface{}, bool) { + v, err := strconv.ParseUint(paramValue, 10, 32) + if err != nil { + return nil, false + } + return uint32(v), true + }). + RegisterFunc("min", func(min uint32) func(uint32) bool { + return func(paramValue uint32) bool { + return paramValue >= min + } + }). + RegisterFunc("max", func(max uint32) func(uint32) bool { + return func(paramValue uint32) bool { + return paramValue <= max + } + }). + RegisterFunc("range", func(min, max uint32) func(uint32) bool { + return func(paramValue uint32) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Uint64 as uint64 type + // 0 to 18446744073709551615. + Uint64 = NewMacro("uint64", "", false, false, func(paramValue string) (interface{}, bool) { + v, err := strconv.ParseUint(paramValue, 10, 64) + if err != nil { + return nil, false + } + return v, true + }). + // checks if the param value's uint64 representation is + // bigger or equal than 'min'. + RegisterFunc("min", func(min uint64) func(uint64) bool { + return func(paramValue uint64) bool { + return paramValue >= min + } + }). + // checks if the param value's uint64 representation is + // smaller or equal than 'max'. + RegisterFunc("max", func(max uint64) func(uint64) bool { + return func(paramValue uint64) bool { + return paramValue <= max + } + }). + // checks if the param value's uint64 representation is + // between min and max, including 'min' and 'max'. + RegisterFunc("range", func(min, max uint64) func(uint64) bool { + return func(paramValue uint64) bool { + return !(paramValue < min || paramValue > max) + } + }) + + // Bool or boolean as bool type + // a string which is "1" or "t" or "T" or "TRUE" or "true" or "True" + // or "0" or "f" or "F" or "FALSE" or "false" or "False". + Bool = NewMacro("bool", "boolean", false, false, func(paramValue string) (interface{}, bool) { + // a simple if statement is faster than regex ^(true|false|True|False|t|0|f|FALSE|TRUE)$ + // in this case. + v, err := strconv.ParseBool(paramValue) + if err != nil { + return nil, false + } + return v, true + }) + + alphabeticalEval = MustRegexp("^[a-zA-Z ]+$") + // Alphabetical letter type + // letters only (upper or lowercase) + Alphabetical = NewMacro("alphabetical", "", false, false, func(paramValue string) (interface{}, bool) { + if !alphabeticalEval(paramValue) { + return nil, false + } + return paramValue, true + }) + + fileEval = MustRegexp("^[a-zA-Z0-9_.-]*$") + // File type + // letters (upper or lowercase) + // numbers (0-9) + // underscore (_) + // dash (-) + // point (.) + // no spaces! or other character + File = NewMacro("file", "", false, false, func(paramValue string) (interface{}, bool) { + if !fileEval(paramValue) { + return nil, false + } + return paramValue, true + }) + // Path type + // anything, should be the last part + // + // It allows everything, we have String and Path as different + // types because I want to give the opportunity to the user + // to organise the macro functions based on wildcard or single dynamic named path parameter. + // Should be living in the latest path segment of a route path. + Path = NewMacro("path", "", false, true, nil) + + // Defaults contains the defaults macro and parameters types for the router. + // + // Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details. + Defaults = &Macros{ + String, + Int, + Int8, + Int16, + Int32, + Int64, + Uint, + Uint8, + Uint16, + Uint32, + Uint64, + Bool, + Alphabetical, + Path, + } +) + +// Macros is just a type of a slice of *Macro +// which is responsible to register and search for macros based on the indent(parameter type). +type Macros []*Macro + +// Register registers a custom Macro. +// The "indent" should not be empty and should be unique, it is the parameter type's name, i.e "string". +// The "alias" is optionally and it should be unique, it is the alias of the parameter type. +// "isMaster" and "isTrailing" is for default parameter type and wildcard respectfully. +// The "evaluator" is the function that is converted to an Iris handler which is executed every time +// before the main chain of a route's handlers that contains this macro of the specific parameter type. +// +// Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details. +func (ms *Macros) Register(indent, alias string, isMaster, isTrailing bool, evaluator ParamEvaluator) *Macro { + macro := NewMacro(indent, alias, isMaster, isTrailing, evaluator) + if ms.register(macro) { + return macro + } + return nil +} + +func (ms *Macros) register(macro *Macro) bool { + if macro.Indent() == "" { + return false + } + + cp := *ms + + for _, m := range cp { + // can't add more than one with the same ast characteristics. + if macro.Indent() == m.Indent() { + return false + } + + if alias := macro.Alias(); alias != "" { + if alias == m.Alias() || alias == m.Indent() { + return false + } + } + + if macro.Master() && m.Master() { + return false + } + } + + cp = append(cp, macro) + + *ms = cp + return true +} + +// Unregister removes a macro and its parameter type from the list. +func (ms *Macros) Unregister(indent string) bool { + cp := *ms + + for i, m := range cp { + if m.Indent() == indent { + copy(cp[i:], cp[i+1:]) + cp[len(cp)-1] = nil + cp = cp[:len(cp)-1] + + *ms = cp + return true + } + } + + return false +} + +// Lookup returns the responsible macro for a parameter type, it can return nil. +func (ms *Macros) Lookup(pt ast.ParamType) *Macro { + if m := ms.Get(pt.Indent()); m != nil { + return m + } + + if alias, has := ast.HasAlias(pt); has { + if m := ms.Get(alias); m != nil { + return m + } + } + + return nil +} + +// Get returns the responsible macro for a parameter type, it can return nil. +func (ms *Macros) Get(indentOrAlias string) *Macro { + if indentOrAlias == "" { + return nil + } + + for _, m := range *ms { + if m.Indent() == indentOrAlias { + return m + } + + if m.Alias() == indentOrAlias { + return m + } + } + + return nil +} + +// GetMaster returns the default macro and its parameter type, +// by default it will return the `String` macro which is responsible for the "string" parameter type. +func (ms *Macros) GetMaster() *Macro { + for _, m := range *ms { + if m.Master() { + return m + } + } + + return nil +} + +// GetTrailings returns the macros that have support for wildcards parameter types. +// By default it will return the `Path` macro which is responsible for the "path" parameter type. +func (ms *Macros) GetTrailings() (macros []*Macro) { + for _, m := range *ms { + if m.Trailing() { + macros = append(macros, m) + } + } + + return +} diff --git a/macro/template.go b/macro/template.go new file mode 100644 index 00000000..8e766cb5 --- /dev/null +++ b/macro/template.go @@ -0,0 +1,155 @@ +package macro + +import ( + "reflect" + + "github.com/kataras/iris/core/memstore" + "github.com/kataras/iris/macro/interpreter/ast" + "github.com/kataras/iris/macro/interpreter/parser" +) + +// Template contains a route's path full parsed template. +// +// Fields: +// Src is the raw source of the path, i.e /users/{id:int min(1)} +// Params is the list of the Params that are being used to the +// path, i.e the min as param name and 1 as the param argument. +type Template struct { + // Src is the original template given by the client + Src string `json:"src"` + Params []TemplateParam `json:"params"` +} + +// TemplateParam is the parsed macro parameter's template +// they are being used to describe the param's syntax result. +type TemplateParam struct { + Src string `json:"src"` // the unparsed param'false source + // Type is not useful anywhere here but maybe + // it's useful on host to decide how to convert the path template to specific router's syntax + Type ast.ParamType `json:"type"` + Name string `json:"name"` + Index int `json:"index"` + ErrCode int `json:"errCode"` + TypeEvaluator ParamEvaluator `json:"-"` + Funcs []reflect.Value `json:"-"` + + stringInFuncs []func(string) bool + canEval bool +} + +func (p TemplateParam) preComputed() TemplateParam { + for _, pfn := range p.Funcs { + if fn, ok := pfn.Interface().(func(string) bool); ok { + p.stringInFuncs = append(p.stringInFuncs, fn) + } + } + + // if true then it should be execute the type parameter or its functions + // else it can be ignored, + // i.e {myparam} or {myparam:string} or {myparam:path} -> + // their type evaluator is nil because they don't do any checks and they don't change + // the default parameter value's type (string) so no need for any work). + p.canEval = p.TypeEvaluator != nil || len(p.Funcs) > 0 || p.ErrCode != parser.DefaultParamErrorCode + + return p +} + +// CanEval returns true if this "p" TemplateParam should be evaluated in serve time. +// It is computed before server ran and it is used to determinate if a route needs to build a macro handler (middleware). +func (p *TemplateParam) CanEval() bool { + return p.canEval +} + +// Eval is the most critical part of the TEmplateParam. +// It is responsible to return "passed:true" or "not passed:false" +// if the "paramValue" is the correct type of the registered parameter type +// and all functions, if any, are passed. +// "paramChanger" is the same form of context's Params().Set +// we could accept a memstore.Store or even context.RequestParams +// but this form has been chosed in order to test easier and fully decoupled from a request when necessary. +// +// It is called from the converted macro handler (middleware) +// from the higher-level component of "kataras/iris/macro/handler#MakeHandler". +func (p *TemplateParam) Eval(paramValue string, paramSetter memstore.ValueSetter) bool { + if p.TypeEvaluator == nil { + for _, fn := range p.stringInFuncs { + if !fn(paramValue) { + return false + } + } + return true + } + + newValue, passed := p.TypeEvaluator(paramValue) + if !passed { + return false + } + + if len(p.Funcs) > 0 { + paramIn := []reflect.Value{reflect.ValueOf(newValue)} + for _, evalFunc := range p.Funcs { + // or make it as func(interface{}) bool and pass directly the "newValue" + // but that would not be as easy for end-developer, so keep that "slower": + if !evalFunc.Call(paramIn)[0].Interface().(bool) { // i.e func(paramValue int) bool + return false + } + } + } + + paramSetter.Set(p.Name, newValue) + return true +} + +// Parse takes a full route path and a macro map (macro map contains the macro types with their registered param functions) +// and returns a new Template. +// It builds all the parameter functions for that template +// and their evaluators, it's the api call that makes use the interpeter's parser -> lexer. +func Parse(src string, macros Macros) (Template, error) { + types := make([]ast.ParamType, len(macros)) + for i, m := range macros { + types[i] = m + } + + tmpl := Template{Src: src} + params, err := parser.Parse(src, types) + if err != nil { + return tmpl, err + } + + for idx, p := range params { + m := macros.Lookup(p.Type) + typEval := m.Evaluator + + tmplParam := TemplateParam{ + Src: p.Src, + Type: p.Type, + Name: p.Name, + Index: idx, + ErrCode: p.ErrorCode, + TypeEvaluator: typEval, + } + + for _, paramfn := range p.Funcs { + tmplFn := m.getFunc(paramfn.Name) + if tmplFn == nil { // if not find on this type, check for Master's which is for global funcs too. + if m := macros.GetMaster(); m != nil { + tmplFn = m.getFunc(paramfn.Name) + } + + if tmplFn == nil { // if not found then just skip this param. + continue + } + } + + evalFn := tmplFn(paramfn.Args) + if evalFn.IsNil() || !evalFn.IsValid() || evalFn.Kind() != reflect.Func { + continue + } + tmplParam.Funcs = append(tmplParam.Funcs, evalFn) + } + + tmpl.Params = append(tmpl.Params, tmplParam.preComputed()) + } + + return tmpl, nil +} diff --git a/mvc/controller.go b/mvc/controller.go index 41f37ac2..f7c75eef 100644 --- a/mvc/controller.go +++ b/mvc/controller.go @@ -7,9 +7,9 @@ import ( "github.com/kataras/iris/context" "github.com/kataras/iris/core/router" - "github.com/kataras/iris/core/router/macro" "github.com/kataras/iris/hero" "github.com/kataras/iris/hero/di" + "github.com/kataras/iris/macro" "github.com/kataras/golog" ) @@ -247,7 +247,7 @@ func (c *ControllerActivator) parseMethods() { } func (c *ControllerActivator) parseMethod(m reflect.Method) { - httpMethod, httpPath, err := parseMethod(m, c.isReservedMethod) + httpMethod, httpPath, err := parseMethod(*c.router.Macros(), m, c.isReservedMethod) if err != nil { if err != errSkip { c.addErr(fmt.Errorf("MVC: fail to parse the route path and HTTP method for '%s.%s': %v", c.fullName, m.Name, err)) @@ -283,7 +283,7 @@ func (c *ControllerActivator) Handle(method, path, funcName string, middleware . } // parse a route template which contains the parameters organised. - tmpl, err := macro.Parse(path, c.router.Macros()) + tmpl, err := macro.Parse(path, *c.router.Macros()) if err != nil { c.addErr(fmt.Errorf("MVC: fail to parse the path for '%s.%s': %v", c.fullName, funcName, err)) return nil @@ -338,6 +338,7 @@ func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []ref } // fmt.Printf("for %s | values: %s\n", funcName, funcDependencies) + funcInjector := di.Func(m.Func, funcDependencies...) // fmt.Printf("actual injector's inputs length: %d\n", funcInjector.Length) if funcInjector.Has { @@ -396,6 +397,11 @@ func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []ref in := make([]reflect.Value, n, n) in[0] = ctrl funcInjector.Inject(&in, ctxValue) + + // for idxx, inn := range in { + // println("controller.go: execution: in.Value = "+inn.String()+" and in.Type = "+inn.Type().Kind().String()+" of index: ", idxx) + // } + hero.DispatchFuncResult(ctx, call(in)) return } diff --git a/mvc/controller_handle_test.go b/mvc/controller_handle_test.go index 55e200d4..9864b3ad 100644 --- a/mvc/controller_handle_test.go +++ b/mvc/controller_handle_test.go @@ -37,6 +37,7 @@ type testControllerHandle struct { func (c *testControllerHandle) BeforeActivation(b BeforeActivation) { b.Handle("GET", "/histatic", "HiStatic") b.Handle("GET", "/hiservice", "HiService") + b.Handle("GET", "/hiservice/{ps:string}", "HiServiceBy") b.Handle("GET", "/hiparam/{ps:string}", "HiParamBy") b.Handle("GET", "/hiparamempyinput/{ps:string}", "HiParamEmptyInputBy") } @@ -84,6 +85,10 @@ func (c *testControllerHandle) HiService() string { return c.Service.Say("hi") } +func (c *testControllerHandle) HiServiceBy(v string) string { + return c.Service.Say("hi with param: " + v) +} + func (c *testControllerHandle) HiParamBy(v string) string { return v } @@ -116,7 +121,8 @@ func TestControllerHandle(t *testing.T) { // and can be used in a user-defined, dynamic "mvc handler". e.GET("/hiservice").Expect().Status(httptest.StatusOK). Body().Equal("service: hi") - + e.GET("/hiservice/value").Expect().Status(httptest.StatusOK). + Body().Equal("service: hi with param: value") // this worked with a temporary variadic on the resolvemethodfunc which is not // correct design, I should split the path and params with the rest of implementation // in order a simple template.Src can be given. diff --git a/mvc/controller_method_parser.go b/mvc/controller_method_parser.go index 97c1282e..1deb40ef 100644 --- a/mvc/controller_method_parser.go +++ b/mvc/controller_method_parser.go @@ -4,11 +4,12 @@ import ( "errors" "fmt" "reflect" + "strconv" "strings" "unicode" "github.com/kataras/iris/core/router" - "github.com/kataras/iris/core/router/macro/interpreter/ast" + "github.com/kataras/iris/macro" ) const ( @@ -95,47 +96,25 @@ func (l *methodLexer) peekPrev() (w string) { return w } -var posWords = map[int]string{ - 0: "", - 1: "first", - 2: "second", - 3: "third", - 4: "forth", - 5: "five", - 6: "sixth", - 7: "seventh", - 8: "eighth", - 9: "ninth", - 10: "tenth", - 11: "eleventh", - 12: "twelfth", - 13: "thirteenth", - 14: "fourteenth", - 15: "fifteenth", - 16: "sixteenth", - 17: "seventeenth", - 18: "eighteenth", - 19: "nineteenth", - 20: "twentieth", -} - func genParamKey(argIdx int) string { - return "arg" + posWords[argIdx] // argfirst, argsecond... + return "param" + strconv.Itoa(argIdx) // param0, param1, param2... } type methodParser struct { - lexer *methodLexer - fn reflect.Method + lexer *methodLexer + fn reflect.Method + macros macro.Macros } -func parseMethod(fn reflect.Method, skipper func(string) bool) (method, path string, err error) { +func parseMethod(macros macro.Macros, fn reflect.Method, skipper func(string) bool) (method, path string, err error) { if skipper(fn.Name) { return "", "", errSkip } p := &methodParser{ - fn: fn, - lexer: newMethodLexer(fn.Name), + fn: fn, + lexer: newMethodLexer(fn.Name), + macros: macros, } return p.parse() } @@ -211,34 +190,45 @@ func (p *methodParser) parsePathParam(path string, w string, funcArgPos int) (st var ( paramKey = genParamKey(funcArgPos) // argfirst, argsecond... - paramType = ast.ParamTypeString // default string + m = p.macros.GetMaster() // default (String by-default) + trailings = p.macros.GetTrailings() ) // string, int... - goType := typ.In(funcArgPos).Name() + goType := typ.In(funcArgPos).Kind() nextWord := p.lexer.peekNext() if nextWord == tokenWildcard { p.lexer.skip() // skip the Wildcard word. - paramType = ast.ParamTypePath - } else if pType := ast.LookupParamTypeFromStd(goType); pType != ast.ParamTypeUnExpected { - // it's not wildcard, so check base on our available macro types. - paramType = pType - } else { - if typ.NumIn() > funcArgPos { - // has more input arguments but we are not in the correct - // index now, maybe the first argument was an `iris/context.Context` - // so retry with the "funcArgPos" incremented. - // - // the "funcArgPos" will be updated to the caller as well - // because we return it among the path and the error. - return p.parsePathParam(path, w, funcArgPos+1) + if len(trailings) == 0 { + return "", 0, errors.New("no trailing path parameter found") + } + m = trailings[0] + } else { + // validMacros := p.macros.LookupForGoType(goType) + + // instead of mapping with a reflect.Kind which has its limitation, + // we map the param types with a go type as a string, + // so custom structs such as "user" can be mapped to a macro with indent || alias == "user". + m = p.macros.Get(strings.ToLower(goType.String())) + + if m == nil { + if typ.NumIn() > funcArgPos { + // has more input arguments but we are not in the correct + // index now, maybe the first argument was an `iris/context.Context` + // so retry with the "funcArgPos" incremented. + // + // the "funcArgPos" will be updated to the caller as well + // because we return it among the path and the error. + return p.parsePathParam(path, w, funcArgPos+1) + } + + return "", 0, fmt.Errorf("invalid syntax: the standard go type: %s found in controller's function: %s at position: %d does not match any valid macro", goType, p.fn.Name, funcArgPos) } - return "", 0, errors.New("invalid syntax for " + p.fn.Name) } // /{argfirst:path}, /{argfirst:long}... - path += fmt.Sprintf("/{%s:%s}", paramKey, paramType.String()) + path += fmt.Sprintf("/{%s:%s}", paramKey, m.Indent()) if nextWord == "" && typ.NumIn() > funcArgPos+1 { // By is the latest word but func is expected diff --git a/mvc/controller_test.go b/mvc/controller_test.go index 475b79dc..7103c9e9 100644 --- a/mvc/controller_test.go +++ b/mvc/controller_test.go @@ -365,7 +365,9 @@ func (c *testControllerRelPathFromFunc) EndRequest(ctx context.Context) { } func (c *testControllerRelPathFromFunc) Get() {} -func (c *testControllerRelPathFromFunc) GetBy(int64) {} +func (c *testControllerRelPathFromFunc) GetBy(uint64) {} +func (c *testControllerRelPathFromFunc) GetUint8RatioBy(uint8) {} +func (c *testControllerRelPathFromFunc) GetInt64RatioBy(int64) {} func (c *testControllerRelPathFromFunc) GetAnythingByWildcard(string) {} func (c *testControllerRelPathFromFunc) GetLogin() {} @@ -375,8 +377,10 @@ func (c *testControllerRelPathFromFunc) GetAdminLogin() {} func (c *testControllerRelPathFromFunc) PutSomethingIntoThis() {} -func (c *testControllerRelPathFromFunc) GetSomethingBy(bool) {} -func (c *testControllerRelPathFromFunc) GetSomethingByBy(string, int) {} +func (c *testControllerRelPathFromFunc) GetSomethingBy(bool) {} + +func (c *testControllerRelPathFromFunc) GetSomethingByBy(string, int) {} + func (c *testControllerRelPathFromFunc) GetSomethingNewBy(string, int) {} // two input arguments, one By which is the latest word. func (c *testControllerRelPathFromFunc) GetSomethingByElseThisBy(bool, int) {} // two input arguments @@ -388,8 +392,13 @@ func TestControllerRelPathFromFunc(t *testing.T) { e.GET("/").Expect().Status(iris.StatusOK). Body().Equal("GET:/") - e.GET("/42").Expect().Status(iris.StatusOK). - Body().Equal("GET:/42") + e.GET("/18446744073709551615").Expect().Status(iris.StatusOK). + Body().Equal("GET:/18446744073709551615") + e.GET("/uint8/ratio/255").Expect().Status(iris.StatusOK). + Body().Equal("GET:/uint8/ratio/255") + e.GET("/uint8/ratio/256").Expect().Status(iris.StatusNotFound) + e.GET("/int64/ratio/-42").Expect().Status(iris.StatusOK). + Body().Equal("GET:/int64/ratio/-42") e.GET("/something/true").Expect().Status(iris.StatusOK). Body().Equal("GET:/something/true") e.GET("/something/false").Expect().Status(iris.StatusOK). diff --git a/mvc/param.go b/mvc/param.go index 8b680aee..faa68396 100644 --- a/mvc/param.go +++ b/mvc/param.go @@ -4,8 +4,7 @@ import ( "reflect" "github.com/kataras/iris/context" - "github.com/kataras/iris/core/router/macro" - "github.com/kataras/iris/core/router/macro/interpreter/ast" + "github.com/kataras/iris/macro" ) func getPathParamsForInput(params []macro.TemplateParam, funcIn ...reflect.Type) (values []reflect.Value) { @@ -13,51 +12,40 @@ func getPathParamsForInput(params []macro.TemplateParam, funcIn ...reflect.Type) return } - consumedParams := make(map[int]bool, 0) - for _, in := range funcIn { - for j, p := range params { - if _, consumed := consumedParams[j]; consumed { - continue - } - paramType := p.Type - paramName := p.Name - // fmt.Printf("%s input arg type vs %s param type\n", in.Kind().String(), p.Type.Kind().String()) - if paramType.Assignable(in.Kind()) { - consumedParams[j] = true - // fmt.Printf("param.go: bind path param func for paramName = '%s' and paramType = '%s'\n", paramName, paramType.String()) - values = append(values, makeFuncParamGetter(paramType, paramName)) - } + // consumedParams := make(map[int]bool, 0) + // for _, in := range funcIn { + // for j, p := range params { + // if _, consumed := consumedParams[j]; consumed { + // continue + // } + + // // fmt.Printf("%s input arg type vs %s param type\n", in.Kind().String(), p.Type.Kind().String()) + // if m := macros.Lookup(p.Type); m != nil && m.GoType == in.Kind() { + // consumedParams[j] = true + // // fmt.Printf("param.go: bind path param func for paramName = '%s' and paramType = '%s'\n", paramName, paramType.String()) + // funcDep, ok := context.ParamResolverByKindAndIndex(m.GoType, p.Index) + // // funcDep, ok := context.ParamResolverByKindAndKey(in.Kind(), paramName) + // if !ok { + // // here we can add a logger about invalid parameter type although it should never happen here + // // unless the end-developer modified the macro/macros with a special type but not the context/ParamResolvers. + // continue + // } + // values = append(values, funcDep) + // } + // } + // } + + for i, param := range params { + if len(funcIn) <= i { + return } + funcDep, ok := context.ParamResolverByTypeAndIndex(funcIn[i], param.Index) + if !ok { + continue + } + + values = append(values, funcDep) } return } - -func makeFuncParamGetter(paramType ast.ParamType, paramName string) reflect.Value { - var fn interface{} - - switch paramType { - case ast.ParamTypeInt: - fn = func(ctx context.Context) int { - v, _ := ctx.Params().GetInt(paramName) - return v - } - case ast.ParamTypeLong: - fn = func(ctx context.Context) int64 { - v, _ := ctx.Params().GetInt64(paramName) - return v - } - case ast.ParamTypeBoolean: - fn = func(ctx context.Context) bool { - v, _ := ctx.Params().GetBool(paramName) - return v - } - default: - // string, path... - fn = func(ctx context.Context) string { - return ctx.Params().Get(paramName) - } - } - - return reflect.ValueOf(fn) -} diff --git a/sessions/sessiondb/badger/database.go b/sessions/sessiondb/badger/database.go index 223deafe..5c990e06 100644 --- a/sessions/sessiondb/badger/database.go +++ b/sessions/sessiondb/badger/database.go @@ -7,11 +7,11 @@ import ( "sync/atomic" "time" - "github.com/kataras/golog" "github.com/kataras/iris/core/errors" "github.com/kataras/iris/sessions" "github.com/dgraph-io/badger" + "github.com/kataras/golog" ) // DefaultFileMode used as the default database's "fileMode" @@ -144,7 +144,13 @@ func (db *Database) Get(sid string, key string) (value interface{}) { if err != nil { return err } - // item.ValueCopy + + // return item.Value(func(valueBytes []byte) { + // if err := sessions.DefaultTranscoder.Unmarshal(valueBytes, &value); err != nil { + // golog.Error(err) + // } + // }) + valueBytes, err := item.Value() if err != nil { return err @@ -173,13 +179,25 @@ func (db *Database) Visit(sid string, cb func(key string, value interface{})) { for iter.Rewind(); iter.ValidForPrefix(prefix); iter.Next() { item := iter.Item() + var value interface{} + + // err := item.Value(func(valueBytes []byte) { + // if err := sessions.DefaultTranscoder.Unmarshal(valueBytes, &value); err != nil { + // golog.Error(err) + // } + // }) + + // if err != nil { + // golog.Error(err) + // continue + // } + valueBytes, err := item.Value() if err != nil { golog.Error(err) continue } - var value interface{} if err = sessions.DefaultTranscoder.Unmarshal(valueBytes, &value); err != nil { golog.Error(err) continue diff --git a/sessions/sessiondb/boltdb/database.go b/sessions/sessiondb/boltdb/database.go index fe1c90fe..7a27d5cc 100644 --- a/sessions/sessiondb/boltdb/database.go +++ b/sessions/sessiondb/boltdb/database.go @@ -6,10 +6,11 @@ import ( "runtime" "time" - "github.com/coreos/bbolt" - "github.com/kataras/golog" "github.com/kataras/iris/core/errors" "github.com/kataras/iris/sessions" + + bolt "github.com/etcd-io/bbolt" + "github.com/kataras/golog" ) // DefaultFileMode used as the default database's "fileMode" diff --git a/websocket/connection.go b/websocket/connection.go index 748f8067..4d1ec8ab 100644 --- a/websocket/connection.go +++ b/websocket/connection.go @@ -2,6 +2,7 @@ package websocket import ( "bytes" + "errors" "io" "net" "strconv" @@ -580,7 +581,14 @@ func (c *connection) Wait() { c.startReader() } +// ErrAlreadyDisconnected can be reported on the `Connection#Disconnect` function whenever the caller tries to close the +// connection when it is already closed by the client or the caller previously. +var ErrAlreadyDisconnected = errors.New("already disconnected") + func (c *connection) Disconnect() error { + if c == nil || c.disconnected { + return ErrAlreadyDisconnected + } return c.server.Disconnect(c.ID()) }