mirror of
https://github.com/kataras/iris.git
synced 2025-02-02 23:40:35 +01:00
Merge pull request #1 from kataras/master
Update Former-commit-id: e2a997a5528a69a2d532c36acc8a433094d4fbbe
This commit is contained in:
commit
fcd390878e
|
@ -63,8 +63,8 @@
|
|||
name = "github.com/ryanuber/columnize"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/satori/go.uuid"
|
||||
revision = "5bf94b69c6b68ee1b541973bb8e1144db23a194b"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# History/Changelog
|
||||
# History/Changelog <a href="HISTORY_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a>
|
||||
|
||||
### Looking for free and real-time support?
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# 更新记录
|
||||
# 更新记录 <a href="HISTORY.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a>
|
||||
|
||||
### 想得到免费即时的支持?
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# Iris Web Framework
|
||||
# Iris Web Framework <a href="README_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a> <a href="README_RU.md"><img width="20px" src="https://iris-go.com/images/flag-russia.svg?v=10" /></a>
|
||||
|
||||
<img align="right" width="170px" src="https://iris-go.com/images/icon.svg?v=10" title="logo created by @merry.dii" />
|
||||
<img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=10" title="logo created by @merry.dii" />
|
||||
|
||||
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![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)](_examples/) [![release](https://img.shields.io/badge/release%20-v10.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
|
||||
|
||||
|
|
232
README_RU.md
Normal file
232
README_RU.md
Normal file
|
@ -0,0 +1,232 @@
|
|||
# Веб-фреймворк Iris <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="README_ZH.md"><img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a>
|
||||
|
||||
<img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=10" title="logo created by @merry.dii" />
|
||||
|
||||
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![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)](_examples/) [![release](https://img.shields.io/badge/release%20-v10.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
|
||||
|
||||
Iris - это быстрая, простая, но полнофункциональная и очень эффективная веб-платформа для Go.
|
||||
|
||||
Iris предоставляет красиво выразительную и удобную основу для вашего следующего веб-сайта или API.
|
||||
|
||||
Наконец, настоящий эквивалент expressjs для языка программирования Go.
|
||||
|
||||
Узнайте, что [другие говорят об Iris](#support), и [запустите](https://github.com/kataras/iris/stargazers) этот github-хранилище, чтобы оставаться в курсе последних событий [актуальными](https://facebook.com/iris.framework).
|
||||
|
||||
## Сторонники
|
||||
|
||||
Спасибо всем, кто поддерживал нас! [Поддержать нас](https://opencollective.com/iris#backer)
|
||||
|
||||
<a href="https://opencollective.com/iris#backers" target="_blank"><img src="https://opencollective.com/iris/backers.svg?width=890"></a>
|
||||
|
||||
```sh
|
||||
$ cat example.go
|
||||
```
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "github.com/kataras/iris"
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// Load all templates from the "./views" folder
|
||||
// where extension is ".html" and parse them
|
||||
// using the standard `html/template` package.
|
||||
app.RegisterView(iris.HTML("./views", ".html"))
|
||||
|
||||
// Method: GET
|
||||
// Resource: http://localhost:8080
|
||||
app.Get("/", func(ctx iris.Context) {
|
||||
// Bind: {{.message}} with "Hello world!"
|
||||
ctx.ViewData("message", "Hello world!")
|
||||
// Render template file: ./views/hello.html
|
||||
ctx.View("hello.html")
|
||||
})
|
||||
|
||||
// Method: GET
|
||||
// Resource: http://localhost:8080/user/42
|
||||
//
|
||||
// Need to use a custom regexp instead?
|
||||
// Easy,
|
||||
// just mark the parameter's type to 'string'
|
||||
// which accepts anything and make use of
|
||||
// its `regexp` macro function, i.e:
|
||||
// app.Get("/user/{id:string regexp(^[0-9]+$)}")
|
||||
app.Get("/user/{id:long}", func(ctx iris.Context) {
|
||||
userID, _ := ctx.Params().GetInt64("id")
|
||||
ctx.Writef("User ID: %d", userID)
|
||||
})
|
||||
|
||||
// Start the server using a network address.
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
```
|
||||
|
||||
> Чтобы узнать подробнее о типах пути параметров нажмите [здесь](_examples/routing/dynamic-path/main.go#L31)
|
||||
|
||||
```html
|
||||
<!-- file: ./views/hello.html -->
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello Page</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{{.message}}</h1>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
```sh
|
||||
$ go run example.go
|
||||
Now listening on: http://localhost:8080
|
||||
Application Started. Press CTRL+C to shut down.
|
||||
_
|
||||
```
|
||||
|
||||
## Установка
|
||||
|
||||
Единственное требование [язык программирования Go.](https://golang.org/dl/)
|
||||
|
||||
```sh
|
||||
$ go get -u github.com/kataras/iris
|
||||
```
|
||||
|
||||
Iris использует преимущества функции [из каталога поставщика](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo). Вы получаете действительно воспроизводимые конструкции, так как этот метод защищает от восходящего потока переименований и удалений.
|
||||
|
||||
[![Iris vs .NET Core(C#) vs Node.js (Express)](https://iris-go.com/images/benchmark-new-gray.png)](_benchmarks/README_UNIX.md)
|
||||
|
||||
_Обновлено: [Вторник, 21 ноября 2017 г.](_benchmarks/README_UNIX.md)_
|
||||
|
||||
<details>
|
||||
<summary>Сравнительные тесты сторонних источников по остальным веб-фреймворкам</summary>
|
||||
|
||||
![Comparison with other frameworks](https://raw.githubusercontent.com/smallnest/go-web-framework-benchmark/4db507a22c964c9bc9774c5b31afdc199a0fe8b7/benchmark.png)
|
||||
|
||||
</details>
|
||||
|
||||
## Поддержка
|
||||
|
||||
- Файл [HISTORY](HISTORY.md#mo-01-jenuary-2018--v1000) - ваш лучший друг, он содержит информацию о последних особенностях и всех изменениях
|
||||
- Вы случайно обнаружили ошибку? Опубликуйте ее на [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)
|
||||
- Вам нравится фреймворк? Поделись об этом в Twitter! Люди говорят:
|
||||
|
||||
<a href="https://twitter.com/gelnior/status/769100480706379776">
|
||||
<img src="https://comments.iris-go.com/comment27_mini.png" width="350px">
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
|
||||
<img src="https://comments.iris-go.com/comment28_mini.png" width="350px">
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/_mgale/status/818591490305761280">
|
||||
<img src="https://comments.iris-go.com/comment29_mini.png" width="350px">
|
||||
</a>
|
||||
<a href="https://twitter.com/VeayoX/status/813273328550973440">
|
||||
<img src="https://comments.iris-go.com/comment30_mini.png" width="350px">
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/pvsukale/status/745328224876408832">
|
||||
<img src="https://comments.iris-go.com/comment31_mini.png" width="350px">
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/blainsmith/status/745338092211560453">
|
||||
<img src="https://comments.iris-go.com/comment32_mini.png" width="350px">
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/tjbyte/status/758287014210867200">
|
||||
<img src="https://comments.iris-go.com/comment33_mini.png" width="350px">
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/tangzero/status/751050577220698112">
|
||||
<img src="https://comments.iris-go.com/comment34_mini.png" width="350px">
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/tjbyte/status/758287244947972096">
|
||||
<img src="https://comments.iris-go.com/comment33_2_mini.png" width="350px">
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/ferarias/status/902468752364773376">
|
||||
<img src="https://comments.iris-go.com/comment41.png" width="350px">
|
||||
</a>
|
||||
|
||||
<br/><br/>
|
||||
|
||||
Для получения дополнительной информации о внесении вклада в проект Iris, пожалуйста, проверьте файл [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
[Список всех участников](https://github.com/kataras/iris/graphs/contributors)
|
||||
|
||||
## Учить
|
||||
|
||||
Прежде всего, самый правильный способ начать работу с веб-фрэймворк - изучить основы языка программирования и стандартные возможности `http`. Если Ваше веб-приложение представляет собой очень простой персональный проект без производительности и требований к техническому обслуживанию, тогда Вы возможно захотите развиваться просто со стандартным пакетом. После этого следуйте рекомендациям:
|
||||
|
||||
- Пройдитесь по **100+1** **[примерам](_examples)** и по некоторым [ стартовым Iris наборам](#iris-starter-kits), которые мы создали для вас
|
||||
- Прочтите [godocs](https://godoc.org/github.com/kataras/iris) для любых подробностей
|
||||
- Приготовьте чашечку кофе или чая, что вам больше нравится, и ознакомьтесь с некоторыми [статьями](#articles), которые мы нашли для вас
|
||||
|
||||
### Стартовые наборы IRIS:
|
||||
|
||||
<!-- table form
|
||||
| Description | Link |
|
||||
| -----------|-------------|
|
||||
| Hasura hub starter project with a ready to deploy golang helloworld webapp with IRIS! | https://hasura.io/hub/project/hasura/hello-golang-iris |
|
||||
| A basic web app built in Iris for Go |https://github.com/gauravtiwari/go_iris_app |
|
||||
| A mini social-network created with the awesome Iris💖💖 | https://github.com/iris-contrib/Iris-Mini-Social-Network |
|
||||
| Iris isomorphic react/hot reloadable/redux/css-modules starter kit | https://github.com/iris-contrib/iris-starter-kit |
|
||||
| Demo project with react using typescript and Iris | https://github.com/ionutvilie/react-ts |
|
||||
| Self-hosted Localization Management Platform built with Iris and Angular | https://github.com/iris-contrib/parrot |
|
||||
| Iris + Docker and Kubernetes | https://github.com/iris-contrib/cloud-native-go |
|
||||
| Quickstart for Iris with Nanobox | https://guides.nanobox.io/golang/iris/from-scratch |
|
||||
-->
|
||||
|
||||
1. [Основное веб-приложение, созданное в Iris for Go](https://github.com/gauravtiwari/go_iris_app)
|
||||
2. [Мини-социальная сеть, созданная с удивительным Iris💖💖](https://github.com/iris-contrib/Iris-Mini-Social-Network)
|
||||
3. [Iris isomorphic react/hot reloadable/redux/css-modules starter kit](https://github.com/iris-contrib/iris-starter-kit)
|
||||
4. [Демо-проект с реакцией на использованием машинописного текста и Iris](https://github.com/ionutvilie/react-ts)
|
||||
5. [Самостоятельная платформа управления локализацией, построенная с помощью Iris и Angular](https://github.com/iris-contrib/parrot)
|
||||
6. [Iris + Docker and Kubernetes](https://github.com/iris-contrib/cloud-native-go)
|
||||
7. [Быстрый запуск для Iris с Nanobox](https://guides.nanobox.io/golang/iris/from-scratch)
|
||||
8. [Cтартовый проект Hasura с готовностью применять веб-приложение Golang hello-world с IRIS](https://hasura.io/hub/project/hasura/hello-golang-iris)
|
||||
|
||||
> Вы построили что-то подобное? Дайте нам [знать](https://github.com/kataras/iris/pulls)!
|
||||
|
||||
### Связующее программное обеспечение
|
||||
|
||||
У Iris есть отличный сбор обработчиков[[1]](middleware/)[[2]](https://github.com/iris-contrib/middleware) которые вы можете использовать бок о бок с вашими веб-приложениями. Однако вы не ограничены ими - вы можете использовать стороннее программное обеспечение, совместимое с [net/http](https://golang.org/pkg/net/http/) пакетом, [_examples/convert-handlers](_examples/convert-handlers) покажут вам путь.
|
||||
|
||||
Iris, в отличие от других, на 100% совместим со стандартами, и именно поэтому большинство крупных компаний, которые адаптируют Go к своему рабочему процессу, как и очень известная телевизионная сеть США, доверяют Iris; это всегда актуально, и он будет приведен в соответствии с пакетом - `net/http`, который будет модернизирован Автором Go при каждом новом выпуске языка программирования Go навсегда.
|
||||
|
||||
### Статьи
|
||||
|
||||
* [Приложение Todo MVC с использованием Iris и Vue.js](https://dev.to/kataras/a-todo-mvc-application-using-iris-and-vuejs-1hn9)
|
||||
* [Стартовый проект Hasura с готовностью применять веб-приложение Golang hello-world с IRIS](bit.ly/2lmKaAZ)
|
||||
* [Топ-6 веб-фреймворков для Go на 2017 год
|
||||
](https://blog.usejournal.com/top-6-web-frameworks-for-go-as-of-2017-23270e059c4b)
|
||||
* [Iris Go Framework + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
|
||||
* [Как создать форму загрузки файла с помощью DropzoneJS и Go](https://hackernoon.com/how-to-build-a-file-upload-form-using-dropzonejs-and-go-8fb9f258a991)
|
||||
* [Как отображать существующие файлы на сервере с помощью DropzoneJS и Go](https://hackernoon.com/how-to-display-existing-files-on-server-using-dropzonejs-and-go-53e24b57ba19)
|
||||
* [ Iris, модульная структура сети](https://medium.com/@corebreaker/iris-web-cd684b4685c7)
|
||||
* [ Go vs .NET Core с точки зрения производительности HTTP](https://medium.com/@kataras/go-vs-net-core-in-terms-of-http-performance-7535a61b67b8)
|
||||
* [ Iris Go vs .NET Core Kestrel с точки зрения производительности HTTP
|
||||
](https://hackernoon.com/iris-go-vs-net-core-kestrel-in-terms-of-http-performance-806195dc93d5)
|
||||
* [Как превратить Android-устройство в веб-сервер](https://twitter.com/ThePracticalDev/status/892022594031017988)
|
||||
* [Применение приложения Iris Golang на Hasura](https://medium.com/@HasuraHQ/deploy-an-iris-golang-app-with-backend-apis-in-minutes-25a559bf530b)
|
||||
* [URL-адрес Shortener Service с помощью Go, Iris и Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
|
||||
|
||||
### Получить работу
|
||||
|
||||
Есть много компаний и стартапов, находящиеся в поисках Go веб-разработчиков с опытом работы с Iris как в качестве требования, которые мы подыскиваем для вас каждый день. Мы публикуем эту информацию на нашей [странице в Facebook](https://www.facebook.com/iris.framework). Ставьте Like, чтобы получите уведомления. Мы уже опубликовали некоторые из них.
|
||||
|
||||
### Спонсоры
|
||||
|
||||
Спасибо всем нашим спонсорам! (пожалуйста, попросите вашу компанию также поддержать этот проект с открытым исходным кодом, [став спонсором](https://opencollective.com/iris#sponsor))
|
||||
|
||||
<a href="https://opencollective.com/iris/sponsor/0/website" target="_blank"><img src="https://opencollective.com/iris/sponsor/0/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/iris/sponsor/1/website" target="_blank"><img src="https://opencollective.com/iris/sponsor/1/avatar.svg"></a>
|
||||
|
||||
## Лицензия
|
||||
|
||||
Iris лицензируется в соответствии с [BSD 3-Clause лицензией](LICENSE). Iris - это бесплатное программное обеспечение с открытым исходным кодом на 100%.
|
||||
|
||||
По любым вопросам, касающимся лицензии, отправьте письмо на [почту](mailto:kataras2006@hotmail.com?subject=Iris%20License).
|
|
@ -1,6 +1,6 @@
|
|||
# Iris Web Framework
|
||||
# Iris Web Framework <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="README_RU.md"><img width="20px" src="https://iris-go.com/images/flag-russia.svg?v=10" /></a>
|
||||
|
||||
<img align="right" width="170px" src="https://iris-go.com/images/icon.svg?v=10" title="logo created by @merry.dii" />
|
||||
<img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=10" title="logo created by @merry.dii" />
|
||||
|
||||
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![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)](_examples/) [![release](https://img.shields.io/badge/release%20-v10.0-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
|
||||
|
||||
|
|
|
@ -35,5 +35,10 @@ func main() {
|
|||
ctx.Writef("Visitor: %#v", visitor)
|
||||
})
|
||||
|
||||
app.Post("/post_value", func(ctx iris.Context) {
|
||||
username := ctx.PostValueDefault("Username", "iris")
|
||||
ctx.Writef("Username: %s", username)
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -1663,8 +1663,10 @@ func (ctx *context) form() (form map[string][]string, found bool) {
|
|||
return form, true
|
||||
}
|
||||
|
||||
if form := ctx.request.MultipartForm.Value; len(form) > 0 {
|
||||
return form, true
|
||||
if m := ctx.request.MultipartForm; m != nil {
|
||||
if len(m.Value) > 0 {
|
||||
return m.Value, true
|
||||
}
|
||||
}
|
||||
|
||||
return nil, false
|
||||
|
@ -1856,46 +1858,6 @@ func uploadTo(fh *multipart.FileHeader, destDirectory string) (int64, error) {
|
|||
return io.Copy(out, src)
|
||||
}
|
||||
|
||||
/* Good idea of mine but it doesn't work of course...
|
||||
// Go can't use `io.ReadCloser` function return value the same
|
||||
// as with other function that returns a `multipart.File`, even if
|
||||
// multipart.File is an `io.ReadCloser`.
|
||||
// So comment all those and implement a function inside the context itself.
|
||||
//
|
||||
// Copiable is the interface which should be completed
|
||||
// by files or not that intend to be used inside the `context#CopyFile`.
|
||||
// This interface allows testing file uploads to your http test as well.
|
||||
//
|
||||
// See `CopyFile` for more.
|
||||
// type Copiable interface {
|
||||
// Open() (io.ReadCloser, error)
|
||||
// }
|
||||
//
|
||||
|
||||
|
||||
// CopyFile copies a `context#Copiable` "file", that can be acquired by the second argument of
|
||||
// a `context.FormFile` (*multipart.FileHeader) as well, to the "dest".
|
||||
//
|
||||
// Returns the copied length as int64 and
|
||||
// an error if file is not exist, or new file can't be created or closed at the end.
|
||||
func CopyFile(file Copiable, dest string) (int64, error) {
|
||||
src, err := fileOpen()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
out, err := os.Create(dest)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
return io.Copy(out, src)
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
// Redirect sends a redirect response to the client
|
||||
// to a specific url or relative path.
|
||||
// accepts 2 parameters string and an optional int
|
||||
|
|
|
@ -9,7 +9,7 @@ import (
|
|||
|
||||
// Controller method is DEPRECATED, use the "mvc" subpackage instead, i.e
|
||||
// import "github.com/kataras/iris/mvc" and read its docs among with its new features at:
|
||||
// https://github.com/kataras/iris/blob/master/HISTORY.md#mo-01-jenuary-2018--v10
|
||||
// https://github.com/kataras/iris/blob/master/HISTORY.md#mo-01-jenuary-2018--v1000
|
||||
func (app *Application) Controller(relPath string, c interface{}, _ ...interface{}) []*router.Route {
|
||||
name := mvc.NameOf(c)
|
||||
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
// Package di provides dependency injection for the Iris Hero and Iris MVC new features.
|
||||
// It's used internally by "hero" and "mvc" packages directly.
|
||||
package di
|
||||
|
||||
import "reflect"
|
||||
|
|
|
@ -145,6 +145,8 @@ func (s *FuncInjector) addValue(inputIndex int, value reflect.Value) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
// Retry used to add missing dependencies, i.e path parameter built'n bindings if not already exists
|
||||
// in the `hero.Handler`, once, only for that func injector.
|
||||
func (s *FuncInjector) Retry(retryFn func(inIndex int, inTyp reflect.Type) (reflect.Value, bool)) bool {
|
||||
for _, missing := range s.lost {
|
||||
if missing.found {
|
||||
|
|
|
@ -58,10 +58,15 @@ func IsZero(v reflect.Value) bool {
|
|||
return v.Interface() == zero.Interface()
|
||||
}
|
||||
|
||||
// IndirectValue returns the reflect.Value that "v" points to.
|
||||
// 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)
|
||||
}
|
||||
|
||||
// ValueOf returns the reflect.Value of "o".
|
||||
// If "o" is already a reflect.Value returns "o".
|
||||
func ValueOf(o interface{}) reflect.Value {
|
||||
if v, ok := o.(reflect.Value); ok {
|
||||
return v
|
||||
|
@ -70,6 +75,8 @@ func ValueOf(o interface{}) reflect.Value {
|
|||
return reflect.ValueOf(o)
|
||||
}
|
||||
|
||||
// ValuesOf same as `ValueOf` but accepts a slice of
|
||||
// somethings and returns a slice of reflect.Value.
|
||||
func ValuesOf(valuesAsInterface []interface{}) (values []reflect.Value) {
|
||||
for _, v := range valuesAsInterface {
|
||||
values = append(values, ValueOf(v))
|
||||
|
@ -77,6 +84,9 @@ func ValuesOf(valuesAsInterface []interface{}) (values []reflect.Value) {
|
|||
return
|
||||
}
|
||||
|
||||
// IndirectType returns the value of a pointer-type "typ".
|
||||
// If "typ" is a pointer, array, chan, map or slice it returns its Elem,
|
||||
// otherwise returns the typ as it's.
|
||||
func IndirectType(typ reflect.Type) reflect.Type {
|
||||
switch typ.Kind() {
|
||||
case reflect.Ptr, reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
|
|
|
@ -5,10 +5,18 @@ import (
|
|||
"reflect"
|
||||
)
|
||||
|
||||
// Scope is the struct injector's struct value scope/permant state.
|
||||
// See `Stateless` and `Singleton`.
|
||||
type Scope uint8
|
||||
|
||||
const (
|
||||
// Stateless is the scope that the struct should be different on each binding,
|
||||
// think it like `Request Scoped`, per-request struct for mvc.
|
||||
Stateless Scope = iota
|
||||
// Singleton is the scope that the struct is the same
|
||||
// between calls, it has no dynamic dependencies or
|
||||
// any unexported fields that is not seted on creation,
|
||||
// so it doesn't need to be created on each call/request.
|
||||
Singleton
|
||||
)
|
||||
|
||||
|
@ -169,6 +177,9 @@ func (s *StructInjector) String() (trace string) {
|
|||
return
|
||||
}
|
||||
|
||||
// Inject accepts a destination struct and any optional context value(s),
|
||||
// hero and mvc takes only one context value and this is the `context.Contex`.
|
||||
// It applies the bindings to the "dest" struct. It calls the InjectElem.
|
||||
func (s *StructInjector) Inject(dest interface{}, ctx ...reflect.Value) {
|
||||
if dest == nil {
|
||||
return
|
||||
|
@ -178,6 +189,7 @@ func (s *StructInjector) Inject(dest interface{}, ctx ...reflect.Value) {
|
|||
s.InjectElem(v, ctx...)
|
||||
}
|
||||
|
||||
// InjectElem same as `Inject` but accepts a reflect.Value and bind the necessary fields directly.
|
||||
func (s *StructInjector) InjectElem(destElem reflect.Value, ctx ...reflect.Value) {
|
||||
for _, f := range s.fields {
|
||||
f.Object.Assign(ctx, func(v reflect.Value) {
|
||||
|
@ -186,6 +198,12 @@ func (s *StructInjector) InjectElem(destElem reflect.Value, ctx ...reflect.Value
|
|||
}
|
||||
}
|
||||
|
||||
// Acquire returns a new value of the struct or
|
||||
// the same struct that is used for resolving the dependencies.
|
||||
// If the scope is marked as singleton then it returns the first instance,
|
||||
// otherwise it creates new and returns it.
|
||||
//
|
||||
// See `Singleton` and `Stateless` for more.
|
||||
func (s *StructInjector) Acquire() reflect.Value {
|
||||
if s.Scope == Singleton {
|
||||
return s.initRef
|
||||
|
@ -193,6 +211,10 @@ func (s *StructInjector) Acquire() reflect.Value {
|
|||
return reflect.New(s.elemType)
|
||||
}
|
||||
|
||||
// AcquireSlice same as `Acquire` but it returns a slice of
|
||||
// values structs, this can be used when a struct is passed as an input parameter
|
||||
// on a function, again if singleton then it returns a pre-created slice which contains
|
||||
// the first struct value given by the struct injector's user.
|
||||
func (s *StructInjector) AcquireSlice() []reflect.Value {
|
||||
if s.Scope == Singleton {
|
||||
return s.initRefAsSlice
|
||||
|
|
|
@ -81,7 +81,7 @@ type Config struct {
|
|||
// guarantee that compression will be supported. Currently only "no context
|
||||
// takeover" modes are supported.
|
||||
//
|
||||
// Defauls to false and it should be remain as it is, unless special requirements.
|
||||
// Defaults to false and it should be remain as it is, unless special requirements.
|
||||
EnableCompression bool
|
||||
|
||||
// Subprotocols specifies the server's supported protocols in order of
|
||||
|
|
Loading…
Reference in New Issue
Block a user