Skip to content

Commit

Permalink
create the new FileServer and HandleDir, deprecate the rest APIBuilde…
Browse files Browse the repository at this point in the history
…r/Party static methods and more

relative: #1283 and removing pongo2 from vendor: https://github.com/kataras/iris/issues/1284
  • Loading branch information
kataras committed Jun 21, 2019
1 parent 7974f80 commit 7c78079
Show file tree
Hide file tree
Showing 123 changed files with 1,555 additions and 9,714 deletions.
2 changes: 1 addition & 1 deletion _benchmarks/iris-mvc-templates/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const (
func main() {
app := iris.New()
app.RegisterView(iris.HTML("./views", ".html").Layout("shared/layout.html"))
app.StaticWeb("/public", publicDir)
app.HandleDir("/public", publicDir)
app.OnAnyErrorCode(onError)

mvc.New(app).Handle(new(controllers.HomeController))
Expand Down
14 changes: 7 additions & 7 deletions _examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ Navigate through examples for a better understanding.
- [Write your own custom parameter types](routing/macros/main.go)
- [Reverse routing](routing/reverse/main.go)
- [Custom Router (high-level)](routing/custom-high-level-router/main.go)
- [Custom Wrapper](routing/custom-wrapper/main.go)
- [Custom Wrapper](routing/custom-wrapper/main.go) **UPDATED**
- Custom Context
* [method overriding](routing/custom-context/method-overriding/main.go)
* [new implementation](routing/custom-context/new-implementation/main.go)
Expand Down Expand Up @@ -366,14 +366,14 @@ You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [her
### File Server

- [Favicon](file-server/favicon/main.go)
- [Basic](file-server/basic/main.go)
- [Embedding Files Into App Executable File](file-server/embedding-files-into-app/main.go)
- [Embedding Gziped Files Into App Executable File](file-server/embedding-gziped-files-into-app/main.go)
- [Basic](file-server/basic/main.go) **UPDATED**
- [Embedding Files Into App Executable File](file-server/embedding-files-into-app/main.go) **UPDATED**
- [Embedding Gziped Files Into App Executable File](file-server/embedding-gziped-files-into-app/main.go) **UPDATED**
- [Send/Force-Download Files](file-server/send-files/main.go)
- Single Page Applications
* [single Page Application](file-server/single-page-application/basic/main.go)
* [embedded Single Page Application](file-server/single-page-application/embedded-single-page-application/main.go)
* [embedded Single Page Application with other routes](file-server/single-page-application/embedded-single-page-application-with-other-routes/main.go)
* [single Page Application](file-server/single-page-application/basic/main.go) **UPDATED**
* [embedded Single Page Application](file-server/single-page-application/embedded-single-page-application/main.go) **UPDATED**
* [embedded Single Page Application with other routes](file-server/single-page-application/embedded-single-page-application-with-other-routes/main.go) **UPDATED**

### How to Read from `context.Request() *http.Request`

Expand Down
46 changes: 23 additions & 23 deletions _examples/README_ZH.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
### 概览

- [Hello world!](hello-world/main.go)
- [Hello WebAssemply!](webassembly/basic/main.go) **NEW**
- [Hello WebAssemply!](webassembly/basic/main.go)
- [基础](overview/main.go)
- [教程: 在线人数](tutorial/online-visitors/main.go)
- [教程: 一个“待完成”MVC Application基于Iris和Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
Expand All @@ -21,7 +21,7 @@
- [教程: DropzoneJS 上传](tutorial/dropzonejs)
- [教程: Caddy 服务器使用](tutorial/caddy)
- [教程: Iris + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
- [教程: Apache Kafka的API](tutorial/api-for-apache-kafka) **NEW**
- [教程: Apache Kafka的API](tutorial/api-for-apache-kafka)

### 目录结构

Expand Down Expand Up @@ -105,10 +105,10 @@ app.Get("{root:path}", rootWildcardHandler)
- [自定义 HTTP 错误](routing/http-errors/main.go)
- [动态路径](routing/dynamic-path/main.go)
* [根级通配符路径](routing/dynamic-path/root-wildcard/main.go)
- [编写你自己的参数类型](routing/macros/main.go) **NEW**
- [编写你自己的参数类型](routing/macros/main.go)
- [反向路由](routing/reverse/main.go)
- [自定义路由(高层级)](routing/custom-high-level-router/main.go) **NEW**
- [自定义包装](routing/custom-wrapper/main.go)
- [自定义路由(高层级)](routing/custom-high-level-router/main.go)
- [自定义包装](routing/custom-wrapper/main.go) **更新**
- 自定义上下文
   * [方法重写](routing/custom-context/method-overriding/main.go)
   * [新实现方式](routing/custom-context/new-implementation/main.go)
Expand All @@ -121,8 +121,8 @@ app.Get("{root:path}", rootWildcardHandler)

- [基础](hero/basic/main.go)
- [概览](hero/overview)
- [Sessions](hero/sessions) **NEW**
- [另一种依赖注入的例子和通常的较好实践](hero/smart-contract/main.go) **NEW**
- [Sessions](hero/sessions)
- [另一种依赖注入的例子和通常的较好实践](hero/smart-contract/main.go) ****

### MVC 模式

Expand Down Expand Up @@ -255,14 +255,14 @@ func(c *ExampleController) Get() string |

参考下面的示例

- [Hello world](mvc/hello-world/main.go) **UPDATED**
- [Session Controller](mvc/session-controller/main.go) **UPDATED**
- [Overview - Plus Repository and Service layers](mvc/overview) **UPDATED**
- [Login showcase - Plus Repository and Service layers](mvc/login) **UPDATED**
- [Singleton](mvc/singleton) **NEW**
- [Websocket Controller](mvc/websocket) **NEW**
- [Register Middleware](mvc/middleware) **NEW**
- [Vue.js Todo MVC](tutorial/vuejs-todo-mvc) **NEW**
- [Hello world](mvc/hello-world/main.go) **更新**
- [Session Controller](mvc/session-controller/main.go) **更新**
- [Overview - Plus Repository and Service layers](mvc/overview) **更新**
- [Login showcase - Plus Repository and Service layers](mvc/login) **更新**
- [Singleton](mvc/singleton) ****
- [Websocket Controller](mvc/websocket) ****
- [Register Middleware](mvc/middleware) ****
- [Vue.js Todo MVC](tutorial/vuejs-todo-mvc) ****

### 子域名

Expand Down Expand Up @@ -316,14 +316,14 @@ You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [her
### 文件服务器

- [Favicon](file-server/favicon/main.go)
- [基础操作](file-server/basic/main.go)
- [把文件嵌入应用的可执行文件](file-server/embedding-files-into-app/main.go)
- [嵌入Gzip压缩的文件到可咨询文件](file-server/embedding-gziped-files-into-app/main.go) **NEW**
- [基础操作](file-server/basic/main.go) **更新**
- [把文件嵌入应用的可执行文件](file-server/embedding-files-into-app/main.go) **更新**
- [嵌入Gzip压缩的文件到可咨询文件](file-server/embedding-gziped-files-into-app/main.go) **更新**
- [上传/(强制)下载文件](file-server/send-files/main.go)
- 单页面应用(Single Page Applications)
* [单页面应用](file-server/single-page-application/basic/main.go)
* [嵌入式(embedded)单页面应用](file-server/single-page-application/embedded-single-page-application/main.go)
* [使用额外路由的嵌入式单页面应用](file-server/single-page-application/embedded-single-page-application-with-other-routes/main.go)
* [单页面应用](file-server/single-page-application/basic/main.go) **更新**
* [嵌入式(embedded)单页面应用](file-server/single-page-application/embedded-single-page-application/main.go) **更新**
* [使用额外路由的嵌入式单页面应用](file-server/single-page-application/embedded-single-page-application-with-other-routes/main.go) **更新**

### 如何读取`context.Request() *http.Request`

Expand All @@ -346,7 +346,7 @@ You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [her
- [写入Gzip压缩](http_responsewriter/write-gzip/main.go)
- [流输出Stream Writer](http_responsewriter/stream-writer/main.go)
- [数据传递Transactions](http_responsewriter/transactions/main.go)
- [SSE](http_responsewriter/sse/main.go) **NEW**
- [SSE](http_responsewriter/sse/main.go)
- [SSE (third-party package usage for server sent events第三方库SSE)](http_responsewriter/sse-third-party/main.go)

> The `context/context#ResponseWriter()` returns an enchament version of a http.ResponseWriter, these examples show some places where the Context uses this object. Besides that you can use it as you did before iris.
Expand Down Expand Up @@ -430,7 +430,7 @@ iris websocket库依赖于它自己的[包](https://github.com/kataras/iris/tree
设计这个包的目的是处理原始websockets,虽然它的API和著名的[socket.io](https://socket.io)很像。我最近读了一片文章,并且对我
决定给iris设计一个**快速的**websocket**限定**包并且不是一个向后传递类socket.io的包。你可以阅读这个链接里的文章https://medium.com/@ivanderbyl/why-you-don-t-need-socket-io-6848f1c871cd。

- [Basic](websocket/basic) **NEW**
- [Basic](websocket/basic) ****
* [Server](websocket/basic/server.go)
* [Go Client](websocket/basic/go-client/client.go)
* [Browser Client](websocket/basic/browser/index.html)
Expand Down
4 changes: 2 additions & 2 deletions _examples/cache/simple/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func writeMarkdown(ctx iris.Context) {
ctx.Markdown(markdownContents)
}

/* Note that `StaticWeb` does use the browser's disk caching by-default
therefore, register the cache handler AFTER any StaticWeb calls,
/* Note that `HandleDir` does use the browser's disk caching by-default
therefore, register the cache handler AFTER any HandleDir calls,
for a faster solution that server doesn't need to keep track of the response
navigate to https://github.com/kataras/iris/blob/master/_examples/cache/client-side/main.go */
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
just a text.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Hello App2App3 index</h1>
1 change: 1 addition & 0 deletions _examples/file-server/basic/assets/app2/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Hello App2 index</h1>
54 changes: 32 additions & 22 deletions _examples/file-server/basic/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,48 @@ import (
"github.com/kataras/iris"
)

func main() {
func newApp() *iris.Application {
app := iris.New()

app.Favicon("./assets/favicon.ico")

// enable gzip, optionally:
// if used before the `StaticXXX` handlers then
// the content byte range feature is gone.
// recommend: turn off for large files especially
// when server has low memory,
// turn on for medium-sized files
// or for large-sized files if they are zipped already,
// i.e "zippedDir/file.gz"
//
// app.Use(iris.Gzip)

// first parameter is the request path
// second is the system directory
//
// app.StaticWeb("/css", "./assets/css")
// app.StaticWeb("/js", "./assets/js")
//
app.StaticWeb("/static", "./assets")
// app.HandleDir("/css", "./assets/css")
// app.HandleDir("/js", "./assets/js")

app.HandleDir("/static", "./assets", iris.DirOptions{
// Defaults to "/index.html", if request path is ending with **/*/$IndexName
// then it redirects to **/*(/) which another handler is handling it,
// that another handler, called index handler, is auto-registered by the framework
// if end developer does not managed to handle it by hand.
IndexName: "/index.html",
// When files should served under compression.
Gzip: false,
// List the files inside the current requested directory if `IndexName` not found.
ShowList: false,
// If `ShowList` is true then this function will be used instead of the default one to show the list of files of a current requested directory(dir).
// DirList: func(ctx context.Context, dirName string, dir http.File) error { ... }
//
// Optional validator that loops through each requested resource.
// AssetValidator: func(ctx iris.Context, name string) bool { ... }
})

// You can also register any index handler manually, order of registration does not matter:
// app.Get("/static", [...custom middleware...], func(ctx iris.Context) {
// [...custom code...]
// ctx.ServeFile("./assets/index.html", false)
// })

// http://localhost:8080/static
// http://localhost:8080/static/css/main.css
// http://localhost:8080/static/js/jquery-2.1.1.js
// http://localhost:8080/static/favicon.ico
app.Run(iris.Addr(":8080"))
return app
}

// Note:
// Routing doesn't allows something .StaticWeb("/", "./assets")
//
// To see how you can wrap the router in order to achieve
// wildcard on root path, see "single-page-application".
func main() {
app := newApp()
app.Run(iris.Addr(":8080"))
}
93 changes: 93 additions & 0 deletions _examples/file-server/basic/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package main

import (
"io/ioutil"
"path/filepath"
"strings"
"testing"

"github.com/kataras/iris/httptest"
)

type resource string

func (r resource) contentType() string {
switch filepath.Ext(r.String()) {
case ".js":
return "application/javascript"
case ".css":
return "text/css"
case ".ico":
return "image/x-icon"
case ".html", "":
return "text/html"
default:
return "text/plain"
}
}

func (r resource) String() string {
return string(r)
}

func (r resource) strip(strip string) string {
s := r.String()
return strings.TrimPrefix(s, strip)
}

func (r resource) loadFromBase(dir string) string {
filename := r.String()

filename = r.strip("/static")
if filepath.Ext(filename) == "" {
// root /.
filename = filename + "/index.html"
}

fullpath := filepath.Join(dir, filename)

b, err := ioutil.ReadFile(fullpath)
if err != nil {
panic(fullpath + " failed with error: " + err.Error())
}

result := string(b)

return result
}

func TestFileServerBasic(t *testing.T) {
var urls = []resource{
"/static/css/main.css",
"/static/js/jquery-2.1.1.js",
"/static/favicon.ico",
"/static/app2",
"/static/app2/app2app3",
"/static",
}

app := newApp()
// route := app.GetRouteReadOnly("GET/{file:path}")
// if route == nil {
// app.Logger().Fatalf("expected a route to serve files")
// }

// if expected, got := "./assets", route.StaticDir(); expected != got {
// app.Logger().Fatalf("expected route's static directory to be: '%s' but got: '%s'", expected, got)
// }

// if !route.StaticDirContainsIndex() {
// app.Logger().Fatalf("epxected ./assets to contain an %s file", "/index.html")
// }

e := httptest.New(t, app)
for _, u := range urls {
url := u.String()
contents := u.loadFromBase("./assets")

e.GET(url).Expect().
Status(httptest.StatusOK).
ContentType(u.contentType(), app.ConfigurationReadOnly().GetCharset()).
Body().Equal(contents)
}
}
8 changes: 7 additions & 1 deletion _examples/file-server/embedding-files-into-app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,14 @@ import (
// See `file-server/embedding-gziped-files-into-app` example as well.
func newApp() *iris.Application {
app := iris.New()
app.Logger().SetLevel("debug")

app.StaticEmbedded("/static", "./assets", Asset, AssetNames)
app.HandleDir("/static", "./assets", iris.DirOptions{
Asset: Asset,
AssetInfo: AssetInfo,
AssetNames: AssetNames,
ShowList: true,
})

return app
}
Expand Down
11 changes: 10 additions & 1 deletion _examples/file-server/embedding-files-into-app/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,21 @@ var urls = []resource{
}

// if bindata's values matches with the assets/... contents
// and secondly if the StaticEmbedded had successfully registered
// and secondly if the HandleDir had successfully registered
// the routes and gave the correct response.
func TestEmbeddingFilesIntoApp(t *testing.T) {
app := newApp()
e := httptest.New(t, app)

route := app.GetRouteReadOnly("GET/static/{file:path}")
if route == nil {
t.Fatalf("expected a route to serve embedded files")
}

if len(route.StaticSites()) > 0 {
t.Fatalf("not expected a static site, the ./assets directory or its subdirectories do not contain any index.html")
}

if runtime.GOOS != "windows" {
// remove the embedded static favicon for !windows,
// it should be built for unix-specific in order to be work
Expand Down
13 changes: 7 additions & 6 deletions _examples/file-server/embedding-gziped-files-into-app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@ import (
func newApp() *iris.Application {
app := iris.New()

// Note the `GzipAsset` and `GzipAssetNames` are different from `go-bindata`'s `Asset` and `AssetNames,
// that means that you can use both `go-bindata` and `bindata` tools,
// the `go-bindata` can be used for the view engine's `Binary` method
// and the `bindata` with the `StaticEmbeddedGzip` (x8 times faster than the StaticEmbeded with `go-bindata`).
app.StaticEmbeddedGzip("/static", "./assets", GzipAsset, GzipAssetNames)

// Note the `GzipAsset` and `GzipAssetNames` are different from `go-bindata`'s `Asset`,
// do not set the `Gzip` option to true, it's already managed by the kataras/bindata.
app.HandleDir("/static", "./assets", iris.DirOptions{
Asset: GzipAsset,
AssetInfo: GzipAssetInfo,
AssetNames: GzipAssetNames,
})
return app
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ var urls = []resource{
}

// if bindata's values matches with the assets/... contents
// and secondly if the StaticEmbedded had successfully registered
// and secondly if the HandleDir had successfully registered
// the routes and gave the correct response.
func TestEmbeddingGzipFilesIntoApp(t *testing.T) {
app := newApp()
Expand Down
Loading

0 comments on commit 7c78079

Please sign in to comment.