1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-11 05:55:57 +00:00

Publish the new version ✈️ | Look description please!

# FAQ

### Looking for free support?

	http://support.iris-go.com
    https://kataras.rocket.chat/channel/iris

### Looking for previous versions?

    https://github.com/kataras/iris#version

### Should I upgrade my Iris?

Developers are not forced to upgrade if they don't really need it. Upgrade whenever you feel ready.
> Iris uses the [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo) feature, so you get truly reproducible builds, as this method guards against upstream renames and deletes.

**How to upgrade**: Open your command-line and execute this command: `go get -u github.com/kataras/iris`.
For further installation support, please click [here](http://support.iris-go.com/d/16-how-to-install-iris-web-framework).

### About our new home page
    http://iris-go.com

Thanks to [Santosh Anand](https://github.com/santoshanand) the http://iris-go.com has been upgraded and it's really awesome!

[Santosh](https://github.com/santoshanand) is a freelancer, he has a great knowledge of nodejs and express js, Android, iOS, React Native, Vue.js etc, if you need a developer to find or create a solution for your problem or task, please contact with him.

The amount of the next two or three donations you'll send they will be immediately transferred to his own account balance, so be generous please!

Read more at https://github.com/kataras/iris/blob/master/HISTORY.md


Former-commit-id: eec2d71bbe011d6b48d2526eb25919e36e5ad94e
This commit is contained in:
kataras
2017-06-03 23:22:52 +03:00
parent 03bcadadec
commit 5e4b63acb2
330 changed files with 35786 additions and 17316 deletions

View File

@@ -7,9 +7,9 @@ package main
import (
"time"
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/view"
)
const (
@@ -20,39 +20,42 @@ const (
func main() {
app := iris.New()
// output startup banner and error logs on os.Stdout
app.Adapt(iris.DevLogger())
// set the router, you can choose gorillamux too
app.Adapt(httprouter.New())
// set the view engine target to ./templates folder
app.Adapt(view.HTML("./templates", ".html").Reload(true))
app.UseFunc(func(ctx *iris.Context) {
// set the view engine target to ./templates folder
app.AttachView(view.HTML("./templates", ".html").Reload(true))
app.Use(func(ctx context.Context) {
// set the title, current time and a layout in order to be used if and when the next handler(s) calls the .Render function
ctx.ViewData("Title", DefaultTitle)
now := time.Now().Format(app.Config.TimeFormat)
now := time.Now().Format(ctx.Application().ConfigurationReadOnly().GetTimeFormat())
ctx.ViewData("CurrentTime", now)
ctx.ViewLayout(DefaultLayout)
ctx.Next()
})
app.Get("/", func(ctx *iris.Context) {
app.Get("/", func(ctx context.Context) {
ctx.ViewData("BodyMessage", "a sample text here... setted by the route handler")
if err := ctx.Render("index.html", nil); err != nil {
app.Log(iris.DevMode, err.Error())
if err := ctx.View("index.html"); err != nil {
ctx.Application().Log(err.Error())
}
})
app.Get("/about", func(ctx *iris.Context) {
app.Get("/about", func(ctx context.Context) {
ctx.ViewData("Title", "My About Page")
ctx.ViewData("BodyMessage", "about text here... setted by the route handler")
// same file, just to keep things simple.
if err := ctx.Render("index.html", nil); err != nil {
app.Log(iris.DevMode, err.Error())
if err := ctx.View("index.html"); err != nil {
ctx.Application().Log(err.Error())
}
})
// Open localhost:8080 and localhost:8080/about
app.Listen(":8080")
// http://localhost:8080
// http://localhost:8080/about
app.Run(iris.Addr(":8080"))
}
// Notes: ViewData("", myCustomStruct{}) will set this myCustomStruct value as a root binding data,
// so any View("other", "otherValue") will probably fail.
// To clear the binding data: ctx.Set(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey(), nil)

View File

@@ -1,48 +0,0 @@
package main
import (
"io"
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
)
func main() {
app := iris.New()
// output startup banner and error logs on os.Stdout
app.Adapt(iris.DevLogger())
// set the router, you can choose gorillamux too
app.Adapt(httprouter.New())
// Custom Render Policy to override or create new content-type render
// i,e: "text/html" with a prefix,
// we will just write to the writer and return false
// to continue to the next contentType-matched renderer if any.
app.Adapt(iris.RenderPolicy(func(out io.Writer, contentType string, binding interface{}, options ...map[string]interface{}) (bool, error) {
if contentType == "text/html" {
if content, ok := binding.(string); ok {
out.Write([]byte("<pre>My Custom prefix</pre><br/>" + content))
}
}
// continue to the next, no error
// note: if we wanted to stop here we would return true instead of false.
return false, nil
}))
app.Get("", func(ctx *iris.Context) {
// These content-types are not managed by our RenderPolicy:
// text, binary and html content-types are
// not rendered via serializers, you have to
// use the ctx.Render functions instead.
// so something like this:
// ctx.Text(iris.StatusOK, "my text content body here!")
// will NOT work with out custom render policy.
ctx.Render("text/html",
"my text content body here!")
})
app.Listen(":8080")
}

View File

@@ -3,7 +3,6 @@
// templates/hi.html
// DO NOT EDIT!
// NOTE: execute your own look main.go
package main
import (
@@ -69,7 +68,7 @@ func (fi bindataFileInfo) Sys() interface{} {
return nil
}
var _templatesHiHtml = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xb2\xc9\x28\xc9\xcd\xb1\xe3\xe5\xb2\xc9\x48\x4d\x4c\x01\xd1\x25\x99\x25\x39\xa9\x76\x1e\x99\x0a\x9e\x45\x99\xc5\x0a\xd1\x21\x1e\xae\x0a\x21\x9e\x21\x3e\xae\xb1\x36\xfa\x10\x29\xa0\x1a\x7d\x98\xe2\xa4\xfc\x94\x4a\x20\xcd\x69\x93\x61\x08\xd2\x52\x5d\xad\xe7\x97\x98\x9b\x5a\x5b\x0b\x52\x03\x95\x03\x2a\x86\xd8\x00\x08\x00\x00\xff\xff\xed\x0e\xad\x42\x6a\x00\x00\x00")
var _templatesHiHtml = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xb2\xc9\x28\xc9\xcd\xb1\xe3\xe5\xb2\xc9\x48\x4d\x4c\x01\xd1\x25\x99\x25\x39\xa9\x76\xd5\xd5\x7a\x21\x20\x46\x6d\xad\x8d\x3e\x44\x84\x97\xcb\x46\x1f\xa6\x26\x29\x3f\xa5\xd2\x8e\x97\x8b\xd3\x26\xc3\xd0\xce\x23\x53\xa1\xba\x5a\xcf\x2f\x31\x37\xb5\xb6\x16\xa4\x06\x2a\x67\xa3\x0f\x35\x18\x10\x00\x00\xff\xff\x61\x88\xba\x25\x61\x00\x00\x00")
func templatesHiHtmlBytes() ([]byte, error) {
return bindataRead(
@@ -84,7 +83,7 @@ func templatesHiHtml() (*asset, error) {
return nil, err
}
info := bindataFileInfo{name: "templates/hi.html", size: 106, mode: os.FileMode(438), modTime: time.Unix(1487682349, 0)}
info := bindataFileInfo{name: "templates/hi.html", size: 97, mode: os.FileMode(438), modTime: time.Unix(1496244983, 0)}
a := &asset{bytes: bytes, info: info}
return a, nil
}
@@ -185,8 +184,8 @@ type bintree struct {
}
var _bintree = &bintree{nil, map[string]*bintree{
"templates": &bintree{nil, map[string]*bintree{
"hi.html": &bintree{templatesHiHtml, map[string]*bintree{}},
"templates": {nil, map[string]*bintree{
"hi.html": {templatesHiHtml, map[string]*bintree{}},
}},
}}

View File

@@ -1,25 +1,30 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/view"
)
func main() {
app := iris.New()
app.Adapt(iris.DevLogger())
app.Adapt(httprouter.New())
// $ go get -u github.com/jteeuwen/go-bindata/...
// $ go-bindata ./templates/...
// $ go build
// $ ./template_binary
// templates are not used, you can delete the folder and run the example
app.Adapt(view.HTML("./templates", ".html").Binary(Asset, AssetNames))
app.Get("/hi", hi)
app.Listen(":8080")
// $ ./embedding-templates-into-app
// html files are not used, you can delete the folder and run the example
app.AttachView(view.HTML("./templates", ".html").Binary(Asset, AssetNames))
app.Get("/", hi)
// http://localhost:8080
app.Run(iris.Addr(":8080"))
}
func hi(ctx *iris.Context) {
ctx.MustRender("hi.html", struct{ Name string }{Name: "iris"})
type page struct {
Title, Name string
}
func hi(ctx context.Context) {
ctx.ViewData("", page{Title: "Hi Page", Name: "iris"})
ctx.View("hi.html")
}

View File

@@ -1,6 +1,6 @@
<html>
<head>
<title>Hi Iris [THE TITLE]</title>
<title>{{.Title}}</title>
</head>
<body>
<h1>Hi {{.Name}}

View File

@@ -3,9 +3,9 @@ package main
import (
"encoding/xml"
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/gorillamux"
"gopkg.in/kataras/iris.v6/adaptors/view"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/view"
)
// ExampleXML just a test struct to view represents xml content-type
@@ -17,43 +17,61 @@ type ExampleXML struct {
func main() {
app := iris.New()
app.Adapt(iris.DevLogger())
app.Adapt(gorillamux.New())
app.Get("/data", func(ctx *iris.Context) {
ctx.Data(iris.StatusOK, []byte("Some binary data here."))
// Just some general restful render types, none of these has to do anything with templates.
app.Get("/binary", func(ctx context.Context) { // useful when you want force-download of contents of raw bytes form.
ctx.Binary([]byte("Some binary data here."))
})
app.Get("/text", func(ctx *iris.Context) {
ctx.Text(iris.StatusOK, "Plain text here")
app.Get("/text", func(ctx context.Context) {
ctx.Text("Plain text here")
})
app.Get("/json", func(ctx *iris.Context) {
ctx.JSON(iris.StatusOK, map[string]string{"hello": "json"}) // or myjsonStruct{hello:"json}
app.Get("/json", func(ctx context.Context) {
ctx.JSON(map[string]string{"hello": "json"}) // or myjsonStruct{hello:"json}
})
app.Get("/jsonp", func(ctx *iris.Context) {
ctx.JSONP(iris.StatusOK, "callbackName", map[string]string{"hello": "jsonp"})
app.Get("/jsonp", func(ctx context.Context) {
ctx.JSONP(map[string]string{"hello": "jsonp"}, context.JSONP{Callback: "callbackName"})
})
app.Get("/xml", func(ctx *iris.Context) {
ctx.XML(iris.StatusOK, ExampleXML{One: "hello", Two: "xml"}) // or iris.Map{"One":"hello"...}
app.Get("/xml", func(ctx context.Context) {
ctx.XML(ExampleXML{One: "hello", Two: "xml"}) // or context.Map{"One":"hello"...}
})
app.Get("/markdown", func(ctx *iris.Context) {
ctx.Markdown(iris.StatusOK, "# Hello Dynamic Markdown Iris")
app.Get("/markdown", func(ctx context.Context) {
ctx.Markdown([]byte("# Hello Dynamic Markdown -- Iris"))
})
app.Adapt(view.HTML("./templates", ".html"))
app.Get("/template", func(ctx *iris.Context) {
//
ctx.MustRender(
"hi.html", // the file name of the template relative to the './templates'
iris.Map{"Name": "Iris"}, // the .Name inside the ./templates/hi.html
iris.Map{"gzip": false}, // enable gzip for big files
)
// - standard html | view.HTML(...)
// - django | view.Django(...)
// - pug(jade) | view.Pug(...)
// - handlebars | view.Handlebars(...)
// - amber | view.Amber(...)
// with default template funcs:
//
// - {{ urlpath "mynamedroute" "pathParameter_ifneeded" }}
// - {{ render "header.html" }}
// - {{ render_r "header.html" }} // partial relative path to current page
// - {{ yield }}
// - {{ current }}
app.AttachView(view.HTML("./templates", ".html"))
app.Get("/template", func(ctx context.Context) {
ctx.ViewData("Name", "Iris") // the .Name inside the ./templates/hi.html
ctx.Gzip(true) // enable gzip for big files
ctx.View("hi.html") // render the template with the file name relative to the './templates'
})
app.Listen(":8080")
// http://localhost:8080/binary
// http://localhost:8080/text
// http://localhost:8080/json
// http://localhost:8080/jsonp
// http://localhost:8080/xml
// http://localhost:8080/markdown
// http://localhost:8080/template
app.Run(iris.Addr(":8080"))
}

View File

@@ -1,23 +1,43 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/view"
)
func main() {
app := iris.New(iris.Configuration{Gzip: false, Charset: "UTF-8"}) // defaults to these
app := iris.New() // defaults to these
app.Adapt(iris.DevLogger())
app.Adapt(httprouter.New())
// - standard html | view.HTML(...)
// - django | view.Django(...)
// - pug(jade) | view.Pug(...)
// - handlebars | view.Handlebars(...)
// - amber | view.Amber(...)
app.Adapt(view.HTML("./templates", ".html"))
tmpl := view.HTML("./templates", ".html")
tmpl.Reload(true) // reload templates on each request (development mode)
// default template funcs are:
//
// - {{ urlpath "mynamedroute" "pathParameter_ifneeded" }}
// - {{ render "header.html" }}
// - {{ render_r "header.html" }} // partial relative path to current page
// - {{ yield }}
// - {{ current }}
tmpl.AddFunc("greet", func(s string) string {
return "Greetings " + s + "!"
})
app.AttachView(tmpl)
app.Get("/hi", hi)
app.Listen(":8080")
app.Get("/", hi)
// http://localhost:8080
app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8")) // defaults to that but you can change it.
}
func hi(ctx *iris.Context) {
ctx.MustRender("hi.html", struct{ Name string }{Name: "iris"})
func hi(ctx context.Context) {
ctx.ViewData("Title", "Hi Page")
ctx.ViewData("Name", "Iris") // {{.Name}} will render: Iris
// ctx.ViewData("", myCcustomStruct{})
ctx.View("hi.html")
}

View File

@@ -1,6 +1,6 @@
<html>
<head>
<title>Hi Iris</title>
<title>{{.Title}}</title>
</head>
<body>
<h1>Hi {{.Name}} </h1>

View File

@@ -1,9 +1,9 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/view"
)
type mypage struct {
@@ -13,20 +13,19 @@ type mypage struct {
func main() {
app := iris.New()
app.Adapt(iris.DevLogger())
app.Adapt(httprouter.New())
tmpl := view.HTML("./templates", ".html")
tmpl.Layout("layout.html")
app.AttachView(view.HTML("./templates", ".html").Layout("layout.html"))
// TIP: append .Reload(true) to reload the templates on each request.
app.Adapt(tmpl)
app.Get("/", func(ctx *iris.Context) {
ctx.Render("mypage.html", mypage{"My Page title", "Hello world!"}, iris.Map{"gzip": true})
app.Get("/", func(ctx context.Context) {
ctx.Gzip(true)
ctx.ViewData("", mypage{"My Page title", "Hello world!"})
ctx.View("mypage.html")
// Note that: you can pass "layout" : "otherLayout.html" to bypass the config's Layout property
// or iris.NoLayout to disable layout on this render action.
// or view.NoLayout to disable layout on this render action.
// third is an optional parameter
})
app.Listen(":8080")
// http://localhost:8080
app.Run(iris.Addr(":8080"))
}

View File

@@ -4,7 +4,7 @@
</head>
<body>
<h1>Body is:</h1>
<h1>[layout] Body content is below...</h1>
<!-- Render the current template here -->
{{ yield }}
</body>

View File

@@ -1,49 +1,52 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/view"
)
func main() {
app := iris.New()
app.Adapt(iris.DevLogger())
app.Adapt(httprouter.New())
tmpl := view.HTML("./templates", ".html")
tmpl.Layout("layouts/layout.html")
tmpl.Funcs(map[string]interface{}{
"greet": func(s string) string {
return "Greetings " + s + "!"
},
tmpl.AddFunc("greet", func(s string) string {
return "Greetings " + s + "!"
})
app.Adapt(tmpl)
app.AttachView(tmpl)
app.Get("/", func(ctx *iris.Context) {
if err := ctx.Render("page1.html", nil); err != nil {
println(err.Error())
app.Get("/", func(ctx context.Context) {
if err := ctx.View("page1.html"); err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Writef(err.Error())
}
})
// remove the layout for a specific route
app.Get("/nolayout", func(ctx *iris.Context) {
if err := ctx.Render("page1.html", nil, iris.RenderOptions{"layout": iris.NoLayout}); err != nil {
println(err.Error())
app.Get("/nolayout", func(ctx context.Context) {
ctx.ViewLayout(view.NoLayout)
if err := ctx.View("page1.html"); err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Writef(err.Error())
}
})
// set a layout for a party, .Layout should be BEFORE any Get or other Handle party's method
my := app.Party("/my").Layout("layouts/mylayout.html")
{
my.Get("/", func(ctx *iris.Context) {
ctx.MustRender("page1.html", nil)
{ // both of these will use the layouts/mylayout.html as their layout.
my.Get("/", func(ctx context.Context) {
ctx.View("page1.html")
})
my.Get("/other", func(ctx *iris.Context) {
ctx.MustRender("page1.html", nil)
my.Get("/other", func(ctx context.Context) {
ctx.View("page1.html")
})
}
app.Listen(":8080")
// http://localhost:8080
// http://localhost:8080/nolayout
// http://localhost:8080/my
// http://localhost:8080/my/other
app.Run(iris.Addr(":8080"))
}

View File

@@ -1,103 +1,75 @@
// Package main an example on how to naming your routes & use the custom 'url' HTML Template Engine, same for other template engines.
// Package main an example on how to naming your routes & use the custom 'url path' HTML Template Engine, same for other template engines.
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/gorillamux"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/view"
)
func main() {
app := iris.New()
app.Adapt(iris.DevLogger())
app.Adapt(view.HTML("./templates", ".html").Reload(true))
if err := app.AttachView(view.HTML("./templates", ".html").Reload(true)); err != nil {
panic(err)
}
startWithHTTPRouter(app)
// or uncomment
// startWithGorillamux()
mypathRoute, _ := app.Get("/mypath", writePathHandler)
mypathRoute.Name = "my-page1"
app.Listen("localhost:8080")
mypath2Route, err := app.Get("/mypath2/{paramfirst}/{paramsecond}", writePathHandler)
// same as: app.Get("/mypath2/:paramfirst/:paramsecond", writePathHandler)
if err != nil { // catch errors when creating a route or catch them on err := .Run, it's up to you.
panic(err)
}
mypath2Route.Name = "my-page2"
mypath3Route, _ := app.Get("/mypath3/{paramfirst}/statichere/{paramsecond}", writePathHandler)
mypath3Route.Name = "my-page3"
mypath4Route, _ := app.Get("/mypath4/{paramfirst}/statichere/{paramsecond}/{otherparam}/{something:path}", writePathHandler)
// same as: app.Get("/mypath4/:paramfirst/statichere/:paramsecond/:otherparam/*something", writePathHandler)
mypath4Route.Name = "my-page4"
// same with Handle/Func
mypath5Route, _ := app.Handle("GET", "/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{something:path}", writePathHandler)
mypath5Route.Name = "my-page5"
mypath6Route, _ := app.Get("/mypath6/{paramfirst}/{paramsecond}/statichere/{paramThirdAfterStatic}", writePathHandler)
mypath6Route.Name = "my-page6"
app.Get("/", func(ctx context.Context) {
// for /mypath6...
paramsAsArray := []string{"theParam1", "theParam2", "paramThirdAfterStatic"}
ctx.ViewData("ParamsAsArray", paramsAsArray)
if err := ctx.View("page.html"); err != nil {
panic(err)
}
})
app.Get("/redirect/{namedRoute}", func(ctx context.Context) {
routeName := ctx.Params().Get("namedRoute")
r := app.GetRoute(routeName)
if r == nil {
ctx.StatusCode(404)
ctx.Writef("Route with name %s not found", routeName)
return
}
println("The path of " + routeName + "is: " + r.Path)
// if routeName == "my-page1"
// prints: The path of of my-page1 is: /mypath
// if it's a path which takes named parameters
// then use "r.ResolvePath(paramValuesHere)"
ctx.Redirect(r.Path)
// http://localhost:8080/redirect/my-page1 will redirect to -> http://localhost:8080/mypath
})
// http://localhost:8080
// http://localhost/redirect/my-page1
app.Run(iris.Addr(":8080"))
}
func writePathHandler(ctx *iris.Context) {
func writePathHandler(ctx context.Context) {
ctx.Writef("Hello from %s.", ctx.Path())
}
func startWithHTTPRouter(app *iris.Framework) {
app.Adapt(httprouter.New())
app.Get("/mypath", writePathHandler).ChangeName("my-page1")
app.Get("/mypath2/:param1/:param2", writePathHandler).ChangeName("my-page2")
app.Get("/mypath3/:param1/statichere/:param2", writePathHandler).ChangeName("my-page3")
app.Get("/mypath4/:param1/statichere/:param2/:otherparam/*something", writePathHandler).ChangeName("my-page4")
// same with Handle/Func
app.HandleFunc("GET", "/mypath5/:param1/statichere/:param2/:otherparam/anything/*something", writePathHandler).ChangeName("my-page5")
app.Get("/mypath6/:param1/:param2/staticParam/:param3AfterStatic", writePathHandler).ChangeName("my-page6")
app.Get("/", func(ctx *iris.Context) {
// for /mypath6...
paramsAsArray := []string{"param1", "theParam1",
"param2", "theParam2",
"param3AfterStatic", "theParam3"}
if err := ctx.Render("page.html", iris.Map{"ParamsAsArray": paramsAsArray}); err != nil {
panic(err)
}
})
app.Get("/redirect/:namedRoute", func(ctx *iris.Context) {
routeName := ctx.Param("namedRoute")
println("The full uri of " + routeName + "is: " + app.URL(routeName))
// if routeName == "my-page1"
// prints: The full uri of my-page1 is: http://127.0.0.1:8080/mypath
ctx.RedirectTo(routeName)
// http://127.0.0.1:8080/redirect/my-page1 will redirect to -> http://127.0.0.1:8080/mypath
})
}
// for gorillamux adaptor is the same thing, the path syntax is the only thing changed ofc.
// Note: Here, we could use app.RouteParam("param1") without even care what router is being used,
// but I have two examples of the same thing in order to be more understable for you.
func startWithGorillamux(app *iris.Framework) {
app.Adapt(gorillamux.New())
app.Get("/mypath", writePathHandler).ChangeName("my-page1")
app.Get("/mypath2/{param1}/{param2}", writePathHandler).ChangeName("my-page2")
app.Get("/mypath3/{param1}/statichere/{param2}", writePathHandler).ChangeName("my-page3")
app.Get("/mypath4/{param1}/statichere/{param2}/{otherparam}/{something:.*}", writePathHandler).ChangeName("my-page4")
// same with Handle/Func
app.HandleFunc("GET", "/mypath5/{param1}/statichere/{param2}/{otherparam}/anything/{something:.*}", writePathHandler).ChangeName("my-page5")
app.Get("/mypath6/{param1}/{param2}/staticParam/{param3AfterStatic}", writePathHandler).ChangeName("my-page6")
app.Get("/", func(ctx *iris.Context) {
// for /mypath6...
paramsAsArray := []string{"param1", "theParam1",
"param2", "theParam2",
"param3AfterStatic", "theParam3"}
if err := ctx.Render("page.html", iris.Map{"ParamsAsArray": paramsAsArray}); err != nil {
panic(err)
}
})
app.Get("/redirect/{namedRoute}", func(ctx *iris.Context) {
routeName := ctx.Param("namedRoute")
println("The full uri of " + routeName + "is: " + app.URL(routeName))
// if routeName == "my-page1"
// prints: The full uri of my-page1 is: http://127.0.0.1:8080/mypath
ctx.RedirectTo(routeName)
// http://127.0.0.1:8080/redirect/my-page1 will redirect to -> http://127.0.0.1:8080/mypath
})
app.Listen("localhost:8080")
}

View File

@@ -1,29 +1,25 @@
<a href="{{url "my-page1"}}">http://127.0.0.1:8080/mypath</a>
<a href="{{urlpath "my-page1"}}">/mypath</a>
<br />
<br />
<a href="{{url "my-page2" "param1" "theParam1" "param2" "theParam2"}}">http://localhost:8080/mypath2/:param1/:param2</a>
or path only:
<a href="{{urlpath "my-page2" "param1" "theParam1" "param2" "theParam2"}}">/mypath2/:param1/:param2</a>
<a href="{{urlpath "my-page2" "theParam1" "theParam2"}}">/mypath2/{paramfirst}/{paramsecond}</a>
<br />
<br />
<a href="{{url "my-page3" "param1" "theParam1" "param2" "theParam2AfterStatic"}}">
http://localhost:8080/mypath3/:param1/statichere/:param2</a>
<a href="{{urlpath "my-page3" "theParam1" "theParam2AfterStatic"}}">/mypath3/{paramfirst}/statichere/{paramsecond}</a>
<br />
<br />
<a href="{{url "my-page4" "param1" "theParam1" "param2" "theparam2AfterStatic" "otherparam" "otherParam" "something" "matchAnything"}}">http://localhost/mypath4/:param1/statichere/:param2/:otherparam/*something</a>
<a href="{{urlpath "my-page4" "theParam1" "theparam2AfterStatic" "otherParam" "matchAnything"}}">
/mypath4/{paramfirst}/statichere/{paramsecond}/{otherparam}/{something:path}</a>
<br />
<br />
<a href="{{url "my-page5" "param1" "theParam1" "param2" "theParam2AfterStatic" "otherparam" "otherParam" "something" "matchAnythingAfterStatic"}}">
http://localhost:8080/mypath5/:param1/statichere/:param2/:otherparam/anything/*anything</a>
<a href="{{urlpath "my-page5" "theParam1" "theParam2Afterstatichere" "otherParam" "matchAnythingAfterStatic"}}">
/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{anything:path}</a>
<br />
<br />
<a href={{url "my-page6" .ParamsAsArray }}>http://localhost:8080/mypath6/{param1}/{param2}/staticParam/{param3AfterStatic}</a>
<a href={{urlpath "my-page6" .ParamsAsArray }}>
/mypath6/{paramfirst}/{paramsecond}/statichere/{paramThirdAfterStatic}
</a>

View File

@@ -2,52 +2,74 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/gorillamux"
"gopkg.in/kataras/iris.v6/adaptors/view"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/core/router"
"github.com/kataras/iris/view"
)
const (
host = "127.0.0.1:8080"
)
func main() {
app := iris.New()
app.Adapt(iris.DevLogger())
app.Adapt(gorillamux.New())
app.Adapt(view.HTML("./templates", ".html"))
// create a custom path reverser, iris let you define your own host and scheme
// which is useful when you have nginx or caddy in front of iris.
rv := router.NewRoutePathReverser(app, router.WithHost(host), router.WithScheme("http"))
// locate and define our templates as usual.
templates := view.HTML("./templates", ".html")
// add a custom func of "url" and pass the rv.URL as its template function body,
// so {{url "routename" "paramsOrSubdomainAsFirstArgument"}} will work inside our templates.
templates.AddFunc("url", rv.URL)
app.Get("/mypath", emptyHandler).ChangeName("my-page1")
app.Get("/mypath2/{param1}/{param2}", emptyHandler).ChangeName("my-page2")
app.Get("/mypath3/{param1}/statichere/{param2}", emptyHandler).ChangeName("my-page3")
app.Get("/mypath4/{param1}/statichere/{param2}/{otherparam}/{something:.*}", emptyHandler).ChangeName("my-page4")
app.AttachView(templates)
// same with Handle/Func
app.HandleFunc("GET", "/mypath5/{param1}/statichere/{param2}/{otherparam}/anything/{something:.*}", emptyHandler).ChangeName("my-page5")
// wildcard subdomain, will catch username1.... username2.... username3... username4.... username5...
// that our below links are providing via page.html's first argument which is the subdomain.
app.Get("/mypath6/{param1}/{param2}/staticParam/{param3AfterStatic}", emptyHandler).ChangeName("my-page6")
subdomain := app.Party("*.")
app.Get("/", func(ctx *iris.Context) {
// for /mypath6...
paramsAsArray := []string{"param1", "theParam1",
"param2", "theParam2",
"param3AfterStatic", "theParam3"}
mypathRoute, _ := subdomain.Get("/mypath", emptyHandler)
mypathRoute.Name = "my-page1"
if err := ctx.Render("page.html", iris.Map{"ParamsAsArray": paramsAsArray}); err != nil {
mypath2Route, _ := subdomain.Get("/mypath2/{paramfirst}/{paramsecond}", emptyHandler)
mypath2Route.Name = "my-page2"
mypath3Route, _ := subdomain.Get("/mypath3/{paramfirst}/statichere/{paramsecond}", emptyHandler)
mypath3Route.Name = "my-page3"
mypath4Route, _ := subdomain.Get("/mypath4/{paramfirst}/statichere/{paramsecond}/{otherparam}/{something:path}", emptyHandler)
mypath4Route.Name = "my-page4"
mypath5Route, _ := subdomain.Handle("GET", "/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{something:path}", emptyHandler)
mypath5Route.Name = "my-page5"
mypath6Route, err := subdomain.Get("/mypath6/{paramfirst}/{paramsecond}/staticParam/{paramThirdAfterStatic}", emptyHandler)
if err != nil { // catch any route problems when declare a route or on err := app.Run(...); err != nil { panic(err) }
panic(err)
}
mypath6Route.Name = "my-page6"
app.Get("/", func(ctx context.Context) {
// for username5./mypath6...
paramsAsArray := []string{"username5", "theParam1", "theParam2", "paramThirdAfterStatic"}
ctx.ViewData("ParamsAsArray", paramsAsArray)
if err := ctx.View("page.html"); err != nil {
panic(err)
}
})
app.Get("/redirect/{namedRoute}", func(ctx *iris.Context) {
routeName := ctx.Param("namedRoute")
println("The full uri of " + routeName + "is: " + app.URL(routeName))
// if routeName == "my-page1"
// prints: The full uri of my-page1 is: http://127.0.0.1:8080/mypath
ctx.RedirectTo(routeName)
// http://127.0.0.1:8080/redirect/my-page1 will redirect to -> http://127.0.0.1:8080/mypath
})
app.Listen("localhost:8080")
// http://127.0.0.1:8080
app.Run(iris.Addr(host))
}
func emptyHandler(ctx *iris.Context) {
ctx.Writef("Hello from %s.", ctx.Path())
func emptyHandler(ctx context.Context) {
ctx.Writef("Hello from subdomain: %s , you're in path: %s", ctx.Subdomain(), ctx.Path())
}
// Note:
// If you got an empty string on {{ url }} or {{ urlpath }} it means that
// args length are not aligned with the route's parameters length
// or the route didn't found by the passed name.

View File

@@ -1,16 +1,29 @@
<!-- the only difference between normal named routes and dynamic subdomains named routes is that the first argument of url
is the subdomain part instead of named parameter-->
<a href="{{url "dynamic-subdomain1" "username1"}}">username1.127.0.0.1:8080/mypath</a>
<a href="{{url "my-page1" "username1"}}">username1.127.0.0.1:8080/mypath</a>
<br />
<br />
<a href="{{url "dynamic-subdomain2" "username2" "theParam1" "theParam2"}}">username2.127.0.0.1:8080/mypath2/{param1}/{param2}</a>
<a href="{{url "my-page2" "username2" "theParam1" "theParam2"}}">
username2.127.0.0.1:8080/mypath2/{paramfirst}/{paramsecond}
</a>
<br />
<br />
<a href="{{url "dynamic-subdomain3" "username3" "theParam1" "theParam2AfterStatic"}}">username3.127.0.0.1:8080/mypath3/{param1}/statichere/{param2}</a>
<a href="{{url "my-page3" "username3" "theParam1" "theParam2AfterStatic"}}">
username3.127.0.0.1:8080/mypath3/{paramfirst}/statichere/{paramsecond}
</a>
<br />
<br />
<a href="{{url "dynamic-subdomain4" "username4" "theParam1" "theparam2AfterStatic" "otherParam" "matchAnything"}}">username4.127.0.0.1:8080/mypath4/{param1}/statichere/{param2}/{otherParam}/{something:.*}</a>
<a href="{{url "my-page4" "username4" "theParam1" "theparam2AfterStatic" "otherParam" "matchAnything"}}">
username4.127.0.0.1:8080/mypath4/{paramfirst}/statichere/{paramsecond}/{otherParam}/{something:path}
</a>
<br />
<br />
<a href="{{url "dynamic-subdomain5" .ParamsAsArray }}" >username5.127.0.0.1:8080/mypath6/{param1}/{param2}/staticParam/{param3}AfterStatic</a>
<a href="{{url "my-page5" "username5" "theParam1" "theparam2AfterStatic" "otherParam" "matchAnything"}}">
username5.127.0.0.1:8080/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{something:path}
</a>
<br/>
<br/>
<a href="{{url "my-page6" .ParamsAsArray }}">
username5.127.0.0.1:8080/mypath6/{paramfirst}/{paramsecond}/staticParam/{paramThirdAfterStatic}
</a>