README ¶
Iris
Iris is an efficient and well-designed, cross-platform, web framework with robust set of features.
Build your own high-performance web applications and APIs powered by unlimited potentials and portability.
What you say about Iris ✌
If you're coming from Node.js world, this is the expressjs equivalent for the Go Programming Language.
Legends ♡
Juan Sebastián Suárez Valencia donated 20 EUR at September 11 of 2016
Bob Lee donated 20 EUR at September 16 of 2016
Celso Luiz donated 50 EUR at September 29 of 2016
Ankur Srivastava donated 20 EUR at October 2 of 2016
Damon Zhao donated 20 EUR at October 21 of 2016
exponity - consulting & digital transformation donated 30 EUR at November 4 of 2016
Thomas Fritz donated 25 EUR at Jenuary 8 of 2017
Thanos V. donated 20 EUR at Jenuary 16 of 2017
George Opritescu donated 20 EUR at February 7 of 2017
Lex Tang donated 20 EUR at February 22 of 2017
Conrad Steenberg donated 25 EUR at March 23 of 2017
Feature Overview
- Focus on high performance
- Automatically install and serve certificates from https://letsencrypt.org
- Robust routing and middleware ecosystem
- Build RESTful APIs
- Choose your favorite routes' path syntax between httprouter and gorillamux
- Request-Scoped Transactions
- Group API's and subdomains with wildcard support
- Body binding for JSON, XML, Forms, can be extended to use your own custom binders
- More than 50 handy functions to send HTTP responses
- View system: supporting more than 6+ template engines, with prerenders. You can still use your favorite
- Define virtual hosts and (wildcard) subdomains with path level routing
- Graceful shutdown
- Limit request body
- Localization i18N
- Serve static files
- Cache
- Log requests
- Customizable format and output for the logger
- Customizable HTTP errors
- Compression (Gzip)
- Authentication
- OAuth, OAuth2 supporting 27+ popular websites
- JWT
- Basic Authentication
- HTTP Sessions
- Add / Remove trailing slash from the URL with option to redirect
- Redirect requests
- HTTP to HTTPS
- HTTP to HTTPS WWW
- HTTP to HTTPS non WWW
- Non WWW to WWW
- WWW to non WWW
- Highly scalable rich content render (Markdown, JSON, JSONP, XML...)
- Websocket-only API similar to socket.io
- Hot Reload on source code changes
- Typescript integration + Web IDE
- Checks for updates at startup
- Highly customizable
- Feels like you used iris forever, thanks to its Fluent API
- And many others...
Table of Contents
- Level: Beginner
- Level: Intermediate
- Level: Advanced
Installation
The only requirement is the Go Programming Language, at least 1.8
$ go get gopkg.in/kataras/iris.v6
Overview
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/cors"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
)
func main() {
// Receives optional iris.Configuration{}, see ./configuration.go
// for more.
app := iris.New()
// Order doesn't matter,
// You can split it to different .Adapt calls.
// See ./adaptors folder for more.
app.Adapt(
// adapt a logger which prints all errors to the os.Stdout
iris.DevLogger(),
// adapt the adaptors/httprouter or adaptors/gorillamux
httprouter.New(),
// 5 template engines are supported out-of-the-box:
//
// - standard html/template
// - amber
// - django
// - handlebars
// - pug(jade)
//
// Use the html standard engine for all files inside "./views" folder with extension ".html"
view.HTML("./views", ".html"),
// Cors wrapper to the entire application, allow all origins.
cors.New(cors.Options{AllowedOrigins: []string{"*"}}))
// http://localhost:6300
// Method: "GET"
// Render ./views/index.html
app.Get("/", func(ctx *iris.Context) {
ctx.Render("index.html", iris.Map{"Title": "Page Title"}, iris.RenderOptions{"gzip": true})
})
// Group routes, optionally: share middleware, template layout and custom http errors.
userAPI := app.Party("/users", userAPIMiddleware).
Layout("layouts/userLayout.html")
{
// Fire userNotFoundHandler when Not Found
// inside http://localhost:6300/users/*anything
userAPI.OnError(404, userNotFoundHandler)
// http://localhost:6300/users
// Method: "GET"
userAPI.Get("/", getAllHandler)
// http://localhost:6300/users/42
// Method: "GET"
userAPI.Get("/:id", getByIDHandler)
// http://localhost:6300/users
// Method: "POST"
userAPI.Post("/", saveUserHandler)
}
// Start the server at 127.0.0.1:6300
app.Listen(":6300")
}
func userAPIMiddleware(ctx *iris.Context) {
// your code here...
println("Request: " + ctx.Path())
ctx.Next() // go to the next handler(s)
}
func userNotFoundHandler(ctx *iris.Context) {
// your code here...
ctx.HTML(iris.StatusNotFound, "<h1> User page not found </h1>")
}
func getAllHandler(ctx *iris.Context) {
// your code here...
}
func getByIDHandler(ctx *iris.Context) {
// take the :id from the path, parse to integer
// and set it to the new userID local variable.
userID, _ := ctx.ParamInt("id")
// userRepo, imaginary database service <- your only job.
user := userRepo.GetByID(userID)
// send back a response to the client,
// .JSON: content type as application/json; charset="utf-8"
// iris.StatusOK: with 200 http status code.
//
// send user as it is or make use of any json valid golang type,
// like the iris.Map{"username" : user.Username}.
ctx.JSON(iris.StatusOK, user)
}
func saveUserHandler(ctx *iris.Context) {
// your code here...
}
Reload on source code changes
$ go get -u github.com/kataras/rizla
$ cd $GOPATH/src/mywebapp
$ rizla main.go
Reload templates on each incoming request
app.Adapt(view.HTML("./views", ".html").Reload(true))
FAQ & Documentation
-
Official small but practical examples
-
Navigate through community examples too
-
Godocs for deep documentation
-
HISTORY.md is your best friend, version migrations are released there
I'll be glad to talk with you about your awesome feature requests, open a new discussion, you will be heard!
Support
- ⭐ the project, will help you to follow the upcoming features
- Donate, will help me to continue
- Post a feature request or report a bug, will help all of us to build a better web, together
- 🌎 post an article or tweet and share it with your neighbor
Buy me a cup of coffee?
Iris is free and open source but developing it has taken thousands of hours of my time and a large part of my sanity. If you feel this web framework useful to you, it would go a great way to ensuring that I can afford to take the time to continue to develop it.
I spend all my time in the construction of Iris, therefore I have no income value.
Feel free to send any amount through paypal
Please check your e-mail after your donation.
Thanks for your gratitude and finance help ♡
Third Party Middleware
Iris has its own middleware form of func(ctx *iris.Context)
but it's also compatible with all net/http
middleware forms using iris.ToHandler, i.e Negroni's middleware form of func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
.
Here is a small list of Iris compatible middleware, I'm sure you can find more:
Middleware | Author | Description |
---|---|---|
binding | Matt Holt | Data binding from HTTP requests into structs |
cloudwatch | Colin Steele | AWS cloudwatch metrics middleware |
csp | Awake Networks | Content Security Policy (CSP) support |
delay | Jeff Martinez | Add delays/latency to endpoints. Useful when testing effects of high latency |
New Relic Go Agent | Yadvendar Champawat | Official New Relic Go Agent (currently in beta) |
gorelic | Jingwen Owen Ou | New Relic agent for Go runtime |
JWT Middleware | Auth0 | Middleware checks for a JWT on the Authorization header on incoming requests and decodes it |
logrus | Dan Buch | Logrus-based logger |
onthefly | Alexander Rødseth | Generate TinySVG, HTML and CSS on the fly |
permissions2 | Alexander Rødseth | Cookies, users and permissions |
prometheus | Rene Zbinden | Easily create metrics endpoint for the prometheus instrumentation tool |
render | Cory Jacobsen | Render JSON, XML and HTML templates |
RestGate | Prasanga Siripala | Secure authentication for REST API endpoints |
secure | Cory Jacobsen | Middleware that implements a few quick security wins |
stats | Florent Messa | Store information about your web application (response time, etc.) |
VanGoH | Taylor Wrobel | Configurable AWS-Style HMAC authentication middleware |
xrequestid | Andrea Franz | Middleware that assigns a random X-Request-Id header to each request |
digits | Bilal Amarni | Middleware that handles Twitter Digits authentication |
Feel free to put up a PR your middleware!
Testing
The httptest
package is a simple Iris helper for the httpexpect, a new library for End-to-end HTTP and REST API testing for Go.
You can find tests by navigating to the source code, i.e:
- context_test.go
- handler_test.go
- policy_gorillamux_test.go
- policy_httprouter_test.go
- policy_nativerouter_test.go
- policy_routerwrapper_test.go
- policy_sessions_test.go
- response_writer_test.go
- route_test.go
- status_test.go
- transaction_test.go
- serializer_test.go
A simple test is located to ./_examples/advanced/httptest/main_test.go
Philosophy
The Iris philosophy is to provide robust tooling for HTTP, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs. Keep note that, today, iris is faster than nginx itself.
Iris does not force you to use any specific ORM or template engine. Iris is routerless which means you can adapt any router you like, httprouter is the fastest, gorillamux has more features. With support for the most used template engines (5), you can quickly craft the perfect application.
People
The author of Iris is @kataras.
However the real Success of Iris belongs to you with your bug reports and feature requests that made this Framework so Unique.
Contact
Besides the fact that we have a community chat for questions or reports and ideas, stackoverflow section for generic go+iris questions and the iris support for bug reports and feature requests, you can also contact with me, as a person who is always open to help you:
Codename: "√Νεxτ"
License
Unless otherwise noted, the source files are distributed under the MIT License found in the LICENSE file.
Note that some optional components that you may use with Iris requires different license agreements.
Documentation ¶
Overview ¶
Package iris is a web framework which provides efficient and well-designed tools with robust set of features to create your awesome and high-performance web application powered by unlimited potentials and portability.
Source code and other details for the project are available at GitHub:
https://github.com/kataras/iris
Looking for further support?
http://support.iris-go.com
Note: This package is under active development status. Each month a new version is releasing to adapt the latest web trends and technologies.
Basic HTTP API ¶
Iris is a very pluggable ecosystem, router can be customized by adapting a 'RouterBuilderPolicy && RouterReversionPolicy'.
With the power of Iris' router adaptors, developers are able to use any third-party router's path features without any implications to the rest of their API.
A Developer is able to select between two out-of-the-box powerful routers:
Httprouter, it's a custom version of https://github.comjulienschmidt/httprouter, which is edited to support iris' subdomains, reverse routing, custom http errors and a lot features, it should be a bit faster than the original too because of iris' Context. It uses `/mypath/:firstParameter/path/:secondParameter` and `/mypath/*wildcardParamName` .
Gorilla Mux, it's the https://github.com/gorilla/mux which supports subdomains, custom http errors, reverse routing, pattern matching via regex and the rest of the iris' features. It uses `/mypath/{firstParameter:any-regex-valid-here}/path/{secondParameter}` and `/mypath/{wildcardParamName:.*}`
Example code:
package main import ( "gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/httprouter" // <--- or adaptors/gorillamux ) func main() { app := iris.New() app.Adapt(httprouter.New()) // <--- or gorillamux.New() // HTTP Method: GET // PATH: http://127.0.0.1/ // Handler(s): index app.Get("/", index) app.Listen(":80") } func index(ctx *iris.Context) { ctx.HTML(iris.StatusOK, "<h1> Welcome to my page!</h1>") }
Run
$ go run main.go $ iris run main.go ## enables reload on source code changes.
All HTTP methods are supported, users can register handlers for same paths on different methods. The first parameter is the HTTP Method, second parameter is the request path of the route, third variadic parameter should contains one or more iris.Handler/HandlerFunc executed by the registered order when a user requests for that specific resouce path from the server.
Example code:
app := iris.New() app.Handle("GET", "/about", aboutHandler) type aboutHandler struct {} func (a aboutHandler) Serve(ctx *iris.Context){ ctx.HTML("Hello from /about, executed from an iris.Handler") } app.HandleFunc("GET", "/contact", func(ctx *iris.Context){ ctx.HTML(iris.StatusOK, "Hello from /contact, executed from an iris.HandlerFunc") })
In order to make things easier for the user, Iris provides functions for all HTTP Methods. The first parameter is the request path of the route, second variadic parameter should contains one or more iris.HandlerFunc executed by the registered order when a user requests for that specific resouce path from the server.
Example code:
app := iris.New() // Method: "GET" app.Get("/", handler) // Method: "POST" app.Post("/", handler) // Method: "PUT" app.Put("/", handler) // Method: "DELETE" app.Delete("/", handler) // Method: "OPTIONS" app.Options("/", handler) // Method: "TRACE" app.Trace("/", handler) // Method: "CONNECT" app.Connect("/", handler) // Method: "HEAD" app.Head("/", handler) // Method: "PATCH" app.Patch("/", handler) // register the route for all HTTP Methods app.Any("/", handler) func handler(ctx *iris.Context){ ctx.Writef("Hello from method: %s and path: %s", ctx.Method(), ctx.Path()) }
Parameterized Path ¶
Path Parameters' syntax depends on the selected router. This is the only difference between the routers, the registered path form, the API remains the same for both.
Example `gorillamux` code:
package main import ( "gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/gorillamux" ) func main() { app := iris.New() app.Adapt(iris.DevLogger()) app.Adapt(gorillamux.New()) app.OnError(iris.StatusNotFound, func(ctx *iris.Context) { ctx.HTML(iris.StatusNotFound, "<h1> custom http error page </h1>") }) app.Get("/healthcheck", h) gamesMiddleware := func(ctx *iris.Context) { println(ctx.Method() + ": " + ctx.Path()) ctx.Next() } games := app.Party("/games", gamesMiddleware) { // braces are optional of course, it's just a style of code games.Get("/{gameID:[0-9]+}/clans", h) games.Get("/{gameID:[0-9]+}/clans/clan/{publicID:[0-9]+}", h) games.Get("/{gameID:[0-9]+}/clans/search", h) games.Put("/{gameID:[0-9]+}/players/{publicID:[0-9]+}", h) games.Put("/{gameID:[0-9]+}/clans/clan/{publicID:[0-9]+}", h) games.Post("/{gameID:[0-9]+}/clans", h) games.Post("/{gameID:[0-9]+}/players", h) games.Post("/{gameID:[0-9]+}/clans/{publicID:[0-9]+}/leave", h) games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/application", h) games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/application/:action", h) games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/invitation", h) games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/invitation/:action", h) games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/delete", h) games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/promote", h) games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/demote", h) } app.Get("/anything/{anythingparameter:.*}", func(ctx *iris.Context) { s := ctx.Param("anythingparameter") ctx.Writef("The path after /anything is: %s", s) }) p := app.Party("mysubdomain.") // http://mysubdomain.myhost.com/ p.Get("/", h) app.Listen("myhost.com:80") } func h(ctx *iris.Context) { ctx.HTML(iris.StatusOK, "<h1>Path<h1/>"+ctx.Path()) }
Example `httprouter` code:
package main import ( "gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/httprouter" // <---- NEW ) func main() { app := iris.New() app.Adapt(iris.DevLogger()) app.Adapt(httprouter.New()) // <---- NEW app.OnError(iris.StatusNotFound, func(ctx *iris.Context){ ctx.HTML(iris.StatusNotFound, "<h1> custom http error page </h1>") }) app.Get("/healthcheck", h) gamesMiddleware := func(ctx *iris.Context) { println(ctx.Method() + ": " + ctx.Path()) ctx.Next() } games:= app.Party("/games", gamesMiddleware) { // braces are optional of course, it's just a style of code games.Get("/:gameID/clans", h) games.Get("/:gameID/clans/clan/:publicID", h) games.Get("/:gameID/clans/search", h) games.Put("/:gameID/players/:publicID", h) games.Put("/:gameID/clans/clan/:publicID", h) games.Post("/:gameID/clans", h) games.Post("/:gameID/players", h) games.Post("/:gameID/clans/:publicID/leave", h) games.Post("/:gameID/clans/:clanPublicID/memberships/application", h) games.Post("/:gameID/clans/:clanPublicID/memberships/application/:action", h) games.Post("/:gameID/clans/:clanPublicID/memberships/invitation", h) games.Post("/:gameID/clans/:clanPublicID/memberships/invitation/:action", h) games.Post("/:gameID/clans/:clanPublicID/memberships/delete", h) games.Post("/:gameID/clans/:clanPublicID/memberships/promote", h) games.Post("/:gameID/clans/:clanPublicID/memberships/demote", h) } app.Get("/anything/*anythingparameter", func(ctx *iris.Context){ s := ctx.Param("anythingparameter") ctx.Writef("The path after /anything is: %s",s) }) mysubdomain:= app.Party("mysubdomain.") // http://mysubdomain.myhost.com/ mysudomain.Get("/", h) app.Listen("myhost.com:80") } func h(ctx *iris.Context) { ctx.HTML(iris.StatusOK, "<h1>Path<h1/>"+ctx.Path()) }
Grouping Routes ¶
A set of routes that are being groupped by path prefix can (optionally) share the same middleware handlers and template layout. A group can have a nested group too.
`.Party` is being used to group routes, developers can declare an unlimited number of (nested) groups.
Example code:
users:= app.Party("/users", myAuthHandler) // http://myhost.com/users/42/profile users.Get("/:userid/profile", userProfileHandler) // httprouter path parameters // http://myhost.com/users/messages/1 users.Get("/inbox/:messageid", userMessageHandler) app.Listen("myhost.com:80")
Custom HTTP Errors ¶
With iris users are able to register their own handlers for http statuses like 404 not found, 500 internal server error and so on.
Example code:
// when 404 then render the template $templatedir/errors/404.html // *read below for information about the view engine.* app.OnError(iris.StatusNotFound, func(ctx *iris.Context){ ctx.RenderWithstatus(iris.StatusNotFound, "errors/404.html", nil) }) app.OnError(500, func(ctx *iris.Context){ // ... })
Custom http errors can be also be registered to a specific group of routes.
Example code:
games:= app.Party("/games", gamesMiddleware) { games.Get("/{gameID:[0-9]+}/clans", h) // gorillamux path parameters games.Get("/{gameID:[0-9]+}/clans/clan/{publicID:[0-9]+}", h) games.Get("/{gameID:[0-9]+}/clans/search", h) } games.OnError(iris.StatusNotFound, gamesNotFoundHandler)
Static Files
// Favicon serves static favicon // accepts 2 parameters, second is optional // favPath (string), declare the system directory path of the __.ico // requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first, // you can declare your own path if you have more than one favicon (desktop, mobile and so on) // // this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico (nothing special that you can't handle by yourself) // Note that you have to call it on every favicon you have to serve automatically (desktop, mobile and so on) // // panics on error Favicon(favPath string, requestPath ...string) RouteInfo // StaticContent serves bytes, memory cached, on the reqPath // a good example of this is how the websocket server uses that to auto-register the /iris-ws.js StaticContent(reqPath string, cType string, content []byte) RouteInfo // StaticHandler returns a new Handler which serves static files StaticHandler(reqPath string, systemPath string, showList bool, enableGzip bool, exceptRoutes ...RouteInfo) HandlerFunc // StaticWeb returns a handler that serves HTTP requests // with the contents of the file system rooted at directory. // // first parameter: the route path // second parameter: the system directory // third OPTIONAL parameter: the exception routes // (= give priority to these routes instead of the static handler) // for more options look iris.StaticHandler. // // iris.StaticWeb("/static", "./static") // // As a special case, the returned file server redirects any request // ending in "/index.html" to the same path, without the final // "index.html". // // StaticWeb calls the StaticHandler(reqPath, systemPath, listingDirectories: false, gzip: false ). StaticWeb(reqPath string, systemPath string, exceptRoutes ...RouteInfo) RouteInfo // StaticEmbedded used when files are distributed inside the app executable, using go-bindata mostly // First parameter is the request path, the path which the files in the vdir will be served to, for example "/static" // Second parameter is the (virtual) directory path, for example "./assets" // Third parameter is the Asset function // Forth parameter is the AssetNames function StaticEmbedded(reqPath string, vdir string, assetFn func(name string) ([]byte, error), namesFn func() []string) RouteInfo
Example code:
package main import ( "gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/httprouter" ) func main() { app := iris.New() app.Adapt(iris.DevLogger()) app.Adapt(httprouter.New()) app.Favicon("./static/favicons/iris_favicon_32_32.ico") // This will serve the ./static/favicons/iris_favicon_32_32.ico to: 127.0.0.1:8080/favicon.ico // app.Favicon("./static/favicons/iris_favicon_32_32.ico", "/favicon_32_32.ico") // This will serve the ./static/favicons/iris_favicon_32_32.ico to: 127.0.0.1:8080/favicon_32_32.ico app.Get("/", func(ctx *iris.Context) { ctx.HTML(iris.StatusOK, "You should see the favicon now at the side of your browser.") }) app.Listen(":8080") }
Middleware Ecosystem ¶
Middleware is just a concept of ordered chain of handlers. Middleware can be registered globally, per-party, per-subdomain and per-route.
Example code:
// globally // before any routes, appends the middleware to all routes app.UseFunc(func(ctx *iris.Context){ // ... any code here ctx.Next() // in order to continue to the next handler, // if that is missing then the next in chain handlers will be not executed, // useful for authentication middleware }) // globally // after or before any routes, prepends the middleware to all routes app.UseGlobalFunc(handlerFunc1, handlerFunc2, handlerFunc3) // per-route app.Post("/login", authenticationHandler, loginPageHandler) // per-party(group of routes) users := app.Party("/users", usersMiddleware) users.Get("/", usersIndex) // per-subdomain mysubdomain := app.Party("mysubdomain.", firstMiddleware) mysubdomain.UseFunc(secondMiddleware) mysubdomain.Get("/", mysubdomainIndex) // per wildcard, dynamic subdomain dynamicSub := app.Party(".*", firstMiddleware, secondMiddleware) dynamicSub.Get("/", func(ctx *iris.Context){ ctx.Writef("Hello from subdomain: "+ ctx.Subdomain()) }) `iris.ToHandler` converts(by wrapping) any `http.Handler/HandlerFunc` or `func(w http.ResponseWriter,r *http.Request, next http.HandlerFunc)` to an `iris.HandlerFunc`. iris.ToHandler(nativeNethttpHandler)
Let's convert the https://github.com/rs/cors net/http external middleware which returns a `next form` handler.
Example code:
package main import ( "github.com/rs/cors" "gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/gorillamux" ) // newCorsMiddleware returns a new cors middleware // with the provided options. func newCorsMiddleware() iris.HandlerFunc { options := cors.Options{ AllowedOrigins: []string{"*"}, } handlerWithNext := cors.New(options).ServeHTTP // this is the only func you will have to use if you're going // to make use of any external net/http middleware. // iris.ToHandler converts the net/http middleware to an iris-compatible. return iris.ToHandler(handlerWithNext) } func main() { app := iris.New() app.Adapt(gorillamux.New()) // Any registers a route to all http methods. app.Any("/user", newCorsMiddleware(), func(ctx *iris.Context) { // .... }) app.Listen(":8080") }
View Engine ¶
Iris supports 5 template engines out-of-the-box, developers can still use any external golang template engine, as `context.ResponseWriter` is an `io.Writer`.
All of these five template engines have common features with common API, like Layout, Template Funcs, Party-specific layout, partial rendering and more.
The standard html, based on github.com/kataras/go-template/tree/master/html its template parser is the golang.org/pkg/html/template/. Django, based ongithub.com/kataras/go-template/tree/master/django its template parser is the github.com/flosch/pongo2 Pug(Jade), based on github.com/kataras/go-template/tree/master/pug its template parser is the github.com/Joker/jade Handlebars, based on github.com/kataras/go-template/tree/master/handlebars its template parser is the github.com/aymerick/raymond Amber, based on github.com/kataras/go-template/tree/master/amber its template parser is the github.com/eknkc/amber
Example code:
package main import ( "gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/gorillamux" "gopkg.in/kataras/iris.v6/adaptors/view" // <--- it contains all the template engines ) func main() { app := iris.New(iris.Configuration{Gzip: false, Charset: "UTF-8"}) // defaults to these app.Adapt(iris.DevLogger()) app.Adapt(gorillamux.New()) // - standard html | view.HTML(...) // - django | view.Django(...) // - pug(jade) | view.Pug(...) // - handlebars | view.Handlebars(...) // - amber | view.Amber(...) app.Adapt(view.HTML("./templates", ".html")) // <---- use the standard html // default template funcs: // // - {{ url "mynamedroute" "pathParameter_ifneeded"} } // - {{ urlpath "mynamedroute" "pathParameter_ifneeded" }} // - {{ render "header.html" }} // - {{ render_r "header.html" }} // partial relative path to current page // - {{ yield }} // - {{ current }} // // to adapt custom funcs, use: app.Adapt(iris.TemplateFuncsPolicy{"myfunc": func(s string) string { return "hi " + s }}) // usage inside template: {{ hi "kataras"}} app.Get("/hi", func(ctx *iris.Context) { ctx.Render( // the file name of the template relative to the './templates'. "hi.html", iris.Map{"Name": "Iris"}, // the .Name inside the ./templates/hi.html, // you can use any custom struct that you want to bind to the requested template. iris.Map{"gzip": false}, // set to true to enable gzip compression. ) }) // http://127.0.0.1:8080/hi app.Listen(":8080") }
View engine supports bundled(https://github.com/jteeuwen/go-bindata) template files too. go-bindata gives you two functions, asset and assetNames, these can be setted to each of the template engines using the `.Binary` func.
Example code:
djangoEngine := view.Django("./templates", ".html") djangoEngine.Binary(asset, assetNames) app.Adapt(djangoEngine)
A real example can be found here: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/embedding-templates-into-app.
Enable auto-reloading of templates on each request. Useful while developers are in dev mode as they no neeed to restart their app on every template edit.
Example code:
pugEngine := view.Pug("./templates", ".jade") pugEngine.Reload(true) // <--- set to true to re-build the templates on each request. app.Adapt(pugEngine)
Each one of these template engines has different options located here: https://github.com/kataras/iris/tree/v6/adaptors/view .
That's the basics ¶
But you should have a basic idea of the framework by now, we just scratched the surface. If you enjoy what you just saw and want to learn more, please follow the below links:
* Examples: https://github.com/iris-contrib/examples
* Adaptors: https://github.com/kataras/iris/tree/v6/adaptors
* Middleware: https://github.com/kataras/iris/tree/v6/middleware and * https://github.com/iris-contrib/middleware
Package iris is a web framework which provides efficient and well-designed tools with robust set of features to create your awesome and high-performance web application powered by unlimited potentials and portability
For view engines, render engines, sessions, websockets, subdomains, automatic-TLS, context support with 50+ handy http functions, dynamic subdomains, router & routes, parties of subdomains & routes, access control, typescript compiler, basicauth,internalization, logging, and much more,
please visit https://godoc.org/gopkg.in/kataras/iris.v6
Index ¶
- Constants
- Variables
- func CERT(addr string, cert tls.Certificate) (net.Listener, error)
- func CheckForUpdates(force bool)
- func DecodeQuery(path string) string
- func DecodeURL(uri string) string
- func LETSENCRYPT(addr string, serverName string, cacheDirOptional ...string) (net.Listener, error)
- func ParseHost(addr string) string
- func ParseHostname(addr string) string
- func ParsePort(addr string) int
- func ParseScheme(domain string) string
- func Proxy(proxyAddr string, redirectSchemeAndHost string) func(context.Context) error
- func RouteConflicts(r RouteInfo, with string) bool
- func StatusText(code int) string
- func TCP4(addr string) (net.Listener, error)
- func TCPKeepAlive(addr string) (net.Listener, error)
- func TLS(addr, certFile, keyFile string) (net.Listener, error)
- func ToNativeHandler(s *Framework, h Handler) http.Handler
- func UNIX(socketFile string, mode os.FileMode) (net.Listener, error)
- type BodyDecoder
- type Configuration
- type Context
- func (ctx *Context) BeginTransaction(pipe func(transaction *Transaction))
- func (ctx *Context) Data(status int, data []byte) error
- func (ctx *Context) Deadline() (deadline time.Time, ok bool)
- func (ctx *Context) Do()
- func (ctx *Context) Done() <-chan struct{}
- func (ctx *Context) EmitError(statusCode int)
- func (ctx *Context) Err() error
- func (ctx *Context) ExecRoute(r RouteInfo)
- func (ctx *Context) ExecRouteAgainst(r RouteInfo, againstRequestPath string)
- func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (ctx *Context) FormValue(name string) string
- func (ctx *Context) FormValues() map[string][]string
- func (ctx *Context) Framework() *Framework
- func (ctx *Context) Get(key string) interface{}
- func (ctx *Context) GetCookie(name string) string
- func (ctx *Context) GetHandlerName() string
- func (ctx *Context) GetInt(key string) (int, error)
- func (ctx *Context) GetString(key string) string
- func (ctx *Context) HTML(status int, htmlContents string) error
- func (ctx *Context) Host() string
- func (ctx *Context) IsAjax() bool
- func (ctx *Context) IsRecording() (*ResponseRecorder, bool)
- func (ctx *Context) IsStopped() bool
- func (ctx *Context) JSON(status int, v interface{}) error
- func (ctx *Context) JSONP(status int, callback string, v interface{}) error
- func (ctx *Context) Log(mode LogMode, format string, a ...interface{})
- func (ctx *Context) Markdown(status int, markdown string) error
- func (ctx *Context) MarkdownString(markdownText string) string
- func (ctx *Context) MaxAge() int64
- func (ctx *Context) Method() string
- func (ctx *Context) MustRender(name string, binding interface{}, options ...map[string]interface{})
- func (ctx *Context) Next()
- func (ctx *Context) NextHandler() Handler
- func (ctx *Context) NotFound()
- func (ctx *Context) Panic()
- func (ctx *Context) Param(key string) string
- func (ctx *Context) ParamDecoded(key string) string
- func (ctx *Context) ParamInt(key string) (int, error)
- func (ctx *Context) ParamInt64(key string) (int64, error)
- func (ctx *Context) ParamIntWildcard(key string) (int, error)
- func (ctx *Context) ParamValidate(compiledExpr *regexp.Regexp, paramName string) bool
- func (ctx *Context) ParamsLen() (n int)
- func (ctx *Context) ParamsSentence() string
- func (ctx *Context) Path() string
- func (ctx *Context) PostValue(name string) string
- func (ctx *Context) ReadForm(formObject interface{}) error
- func (ctx *Context) ReadJSON(jsonObject interface{}) error
- func (ctx *Context) ReadXML(xmlObject interface{}) error
- func (ctx *Context) Record()
- func (ctx *Context) Recorder() *ResponseRecorder
- func (ctx *Context) Redirect(urlToRedirect string, statusHeader ...int)
- func (ctx *Context) RedirectTo(routeName string, args ...interface{})
- func (ctx *Context) RemoteAddr() string
- func (ctx *Context) RemoveCookie(name string)
- func (ctx *Context) Render(name string, binding interface{}, options ...map[string]interface{}) error
- func (ctx *Context) RenderWithStatus(status int, name string, binding interface{}, ...) (err error)
- func (ctx *Context) RequestHeader(k string) string
- func (ctx *Context) RequestPath(escape bool) string
- func (ctx *Context) SendFile(filename string, destinationName string) error
- func (ctx *Context) ServeContent(content io.ReadSeeker, filename string, modtime time.Time, ...) error
- func (ctx *Context) ServeFile(filename string, gzipCompression bool) error
- func (ctx *Context) ServerHost() string
- func (ctx *Context) Session() Session
- func (ctx *Context) SessionDestroy()
- func (ctx *Context) Set(key string, value interface{})
- func (ctx *Context) SetClientCachedBody(status int, bodyContent []byte, cType string, modtime time.Time) error
- func (ctx *Context) SetContentType(s string)
- func (ctx *Context) SetCookie(cookie *http.Cookie)
- func (ctx *Context) SetCookieKV(name, value string)
- func (ctx *Context) SetHeader(k string, v string)
- func (ctx *Context) SetMaxRequestBodySize(limitOverBytes int64)
- func (ctx *Context) SetStatusCode(statusCode int)
- func (ctx *Context) SkipTransactions()
- func (ctx *Context) StopExecution()
- func (ctx *Context) StreamWriter(writer func(w io.Writer) bool)
- func (ctx *Context) Subdomain() (subdomain string)
- func (ctx *Context) Text(status int, text string) error
- func (ctx *Context) TransactionsSkipped() bool
- func (ctx *Context) Translate(format string, args ...interface{}) string
- func (ctx *Context) TryWriteGzip(b []byte) (int, error)
- func (ctx *Context) URLParam(key string) string
- func (ctx *Context) URLParamInt(key string) (int, error)
- func (ctx *Context) URLParamInt64(key string) (int64, error)
- func (ctx *Context) URLParams() map[string]string
- func (ctx *Context) URLParamsAsMulti() map[string][]string
- func (ctx *Context) UnmarshalBody(v interface{}, unmarshaler Unmarshaler) error
- func (ctx *Context) Value(key interface{}) interface{}
- func (ctx *Context) ValuesLen() (n int)
- func (ctx *Context) ViewData(key string, value interface{})
- func (ctx *Context) ViewLayout(layoutTmplFile string)
- func (ctx *Context) VirtualHostname() string
- func (ctx *Context) VisitAllCookies(visitor func(key string, value string))
- func (ctx *Context) VisitValues(visitor func(string, interface{}))
- func (ctx *Context) WriteGzip(b []byte) (int, error)
- func (ctx *Context) XML(status int, v interface{}) error
- type ContextPool
- type ErrorHandlers
- func (e *ErrorHandlers) Fire(statusCode int, ctx *Context)
- func (e *ErrorHandlers) Get(statusCode int) Handler
- func (e *ErrorHandlers) GetOrRegister(statusCode int) Handler
- func (e *ErrorHandlers) Register(statusCode int, handler Handler)
- func (e *ErrorHandlers) RegisterRegex(statusCode int, handler Handler, expr string) error
- type EventListener
- type EventPolicy
- type Framework
- func (s *Framework) Adapt(policies ...Policy)
- func (s *Framework) Boot() (firstTime bool)
- func (s *Framework) Cache(bodyHandler HandlerFunc, expiration time.Duration) HandlerFunc
- func (s *Framework) Listen(addr string)
- func (s *Framework) ListenLETSENCRYPT(addr string, cacheFileOptional ...string)
- func (s *Framework) ListenTLS(addr string, certFile, keyFile string)
- func (s *Framework) ListenUNIX(socketFile string, mode os.FileMode)
- func (s *Framework) Log(mode LogMode, log string)
- func (s *Framework) Must(err error)
- func (s *Framework) Path(routeName string, args ...interface{}) string
- func (s *Framework) Regex(pairParamExpr ...string) HandlerFunc
- func (s *Framework) RegexSingle(paramName string, expr string, onFail HandlerFunc) HandlerFunc
- func (s *Framework) Render(w io.Writer, name string, bind interface{}, options ...map[string]interface{}) error
- func (s *Framework) RouteParam(paramName string) string
- func (s *Framework) RouteWildcardPath(path string, paramName string) string
- func (s *Framework) Serve(ln net.Listener) error
- func (s *Framework) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Framework) Set(setters ...OptionSetter)
- func (s *Framework) URL(routeName string, args ...interface{}) (url string)
- type Handler
- type HandlerFunc
- type LogMode
- type LoggerPolicy
- type Map
- type MethodChangedListener
- type Middleware
- type OptionSet
- type OptionSetter
- type Policies
- type Policy
- type RenderOptions
- type RenderPolicy
- type ResponseRecorder
- func (w *ResponseRecorder) Body() []byte
- func (w ResponseRecorder) CloseNotify() <-chan bool
- func (w ResponseRecorder) ContentType() string
- func (w *ResponseRecorder) Flush()
- func (w *ResponseRecorder) Header() http.Header
- func (w ResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *ResponseRecorder) Push(target string, opts *http.PushOptions) error
- func (w *ResponseRecorder) ReseAllHeaders()
- func (w *ResponseRecorder) Reset()
- func (w *ResponseRecorder) ResetBody()
- func (w *ResponseRecorder) ResetHeaders()
- func (w ResponseRecorder) SetBeforeFlush(cb func())
- func (w *ResponseRecorder) SetBody(b []byte)
- func (w *ResponseRecorder) SetBodyString(s string)
- func (w ResponseRecorder) SetContentType(cType string)
- func (w ResponseRecorder) StatusCode() int
- func (w *ResponseRecorder) Write(contents []byte) (int, error)
- func (w ResponseRecorder) WriteHeader(statusCode int)
- func (w *ResponseRecorder) WriteString(s string) (n int, err error)
- func (w *ResponseRecorder) Writef(format string, a ...interface{}) (n int, err error)
- type ResponseWriter
- type RouteInfo
- type RouteRepository
- type Router
- func (router *Router) Any(registeredPath string, handlersFn ...HandlerFunc)
- func (router *Router) Connect(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Delete(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Done(handlers ...Handler) *Router
- func (router *Router) DoneFunc(handlersFn ...HandlerFunc) *Router
- func (router *Router) EmitError(statusCode int, ctx *Context)
- func (router *Router) Favicon(favPath string, requestPath ...string) RouteInfo
- func (router *Router) Get(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Handle(method string, registeredPath string, handlers ...Handler) RouteInfo
- func (router *Router) HandleFunc(method string, registeredPath string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Head(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Layout(tmplLayoutFile string) *Router
- func (router *Router) None(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) OnError(statusCode int, handlerFn HandlerFunc, rgexp ...string)
- func (router *Router) Options(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Party(relativePath string, handlersFn ...HandlerFunc) *Router
- func (router *Router) Patch(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Post(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Put(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Routes() RoutesInfo
- func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (router *Router) StaticContent(reqPath string, cType string, content []byte) RouteInfo
- func (router *Router) StaticEmbedded(requestPath string, vdir string, assetFn func(name string) ([]byte, error), ...) RouteInfo
- func (router *Router) StaticHandler(reqPath string, systemPath string, showList bool, enableGzip bool, ...) HandlerFunc
- func (router *Router) StaticServe(systemPath string, requestPath ...string) RouteInfo
- func (router *Router) StaticWeb(reqPath string, systemPath string, exceptRoutes ...RouteInfo) RouteInfo
- func (router *Router) Trace(path string, handlersFn ...HandlerFunc) RouteInfo
- func (router *Router) Use(handlers ...Handler) *Router
- func (router *Router) UseFunc(handlersFn ...HandlerFunc) *Router
- func (router *Router) UseGlobal(handlers ...Handler)
- func (router *Router) UseGlobalFunc(handlersFn ...HandlerFunc)
- type RouterBuilderPolicy
- type RouterReversionPolicy
- type RouterWrapperPolicy
- type RoutesInfo
- type Session
- type SessionsPolicy
- type StaticHandlerBuilder
- type TCPKeepAliveListener
- type TemplateFuncsPolicy
- type Transaction
- type TransactionErrResult
- type TransactionScope
- type TransactionScopeFunc
- type Unmarshaler
- type UnmarshalerFunc
Constants ¶
const ( // SchemeHTTPS returns "https://" (full) SchemeHTTPS = "https://" // SchemeHTTP returns "http://" (full) SchemeHTTP = "http://" )
const ( NoCompressionLevel = 0 BestSpeedLevel = 1 BestCompressionLevel = 9 DefaultCompressionLevel = -1 ConstantCompressionLevel = -2 // Does only Huffman encoding )
These constants are copied from the standard flate package available Compressors
const ( DefaultDisablePathCorrection = false DefaultEnablePathEscape = false DefaultCharset = "UTF-8" // Per-connection buffer size for requests' reading. // This also limits the maximum header size. // // Increase this buffer if your clients send multi-KB RequestURIs // and/or multi-KB headers (for example, BIG cookies). // // Default buffer size is 8MB DefaultMaxHeaderBytes = 8096 // DefaultReadTimeout no read client timeout DefaultReadTimeout = 0 // DefaultWriteTimeout no serve client timeout DefaultWriteTimeout = 0 )
Default values for base Iris conf
const ( // DefaultServerHostname returns the default hostname which is 0.0.0.0 DefaultServerHostname = "0.0.0.0" // DefaultServerPort returns the default port which is 8080, not used DefaultServerPort = 8080 )
Default values for base Server conf
const ( // NoLayout to disable layout for a particular template file NoLayout = "@.|.@no_layout@.|.@" // ViewLayoutContextKey is the name of the user values which can be used to set a template layout from a middleware and override the parent's ViewLayoutContextKey = "@viewLayout" ViewDataContextKey = "@viewData" // conversions // TemplateLayoutContextKey same as ViewLayoutContextKey TemplateLayoutContextKey = ViewLayoutContextKey )
const ( // MethodGet "GET" MethodGet = "GET" // MethodPost "POST" MethodPost = "POST" // MethodPut "PUT" MethodPut = "PUT" // MethodDelete "DELETE" MethodDelete = "DELETE" // MethodConnect "CONNECT" MethodConnect = "CONNECT" // MethodHead "HEAD" MethodHead = "HEAD" // MethodPatch "PATCH" MethodPatch = "PATCH" // MethodOptions "OPTIONS" MethodOptions = "OPTIONS" // MethodTrace "TRACE" MethodTrace = "TRACE" // MethodNone is a Virtual method // to store the "offline" routes MethodNone = "NONE" )
const ( StatusContinue = 100 // RFC 7231, 6.2.1 StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusOK = 200 // RFC 7231, 6.3.1 StatusCreated = 201 // RFC 7231, 6.3.2 StatusAccepted = 202 // RFC 7231, 6.3.3 StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4 StatusNoContent = 204 // RFC 7231, 6.3.5 StatusResetContent = 205 // RFC 7231, 6.3.6 StatusPartialContent = 206 // RFC 7233, 4.1 StatusMultiStatus = 207 // RFC 4918, 11.1 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 StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7 StatusPermanentRedirect = 308 // RFC 7538, 3 StatusBadRequest = 400 // RFC 7231, 6.5.1 StatusPaymentRequired = 402 // RFC 7231, 6.5.2 StatusForbidden = 403 // RFC 7231, 6.5.3 StatusNotFound = 404 // RFC 7231, 6.5.4 StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5 StatusNotAcceptable = 406 // RFC 7231, 6.5.6 StatusProxyAuthRequired = 407 // RFC 7235, 3.2 StatusRequestTimeout = 408 // RFC 7231, 6.5.7 StatusConflict = 409 // RFC 7231, 6.5.8 StatusGone = 410 // RFC 7231, 6.5.9 StatusLengthRequired = 411 // RFC 7231, 6.5.10 StatusPreconditionFailed = 412 // RFC 7232, 4.2 StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11 StatusRequestURITooLong = 414 // RFC 7231, 6.5.12 StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13 StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4 StatusExpectationFailed = 417 // RFC 7231, 6.5.14 StatusTeapot = 418 // RFC 7168, 2.3.3 StatusUnprocessableEntity = 422 // RFC 4918, 11.2 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusUpgradeRequired = 426 // RFC 7231, 6.5.15 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 StatusGatewayTimeout = 504 // RFC 7231, 6.6.5 StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6 StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 StatusInsufficientStorage = 507 // RFC 4918, 11.5 StatusLoopDetected = 508 // RFC 5842, 7.2 StatusNotExtended = 510 // RFC 2774, 7 StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6 )
HTTP status codes.
const (
// DynamicSubdomainIndicator where a registered path starts with '*.' then it contains a dynamic subdomain, if subdomain == "*." then its dynamic
DynamicSubdomainIndicator = "*."
)
const RouterNameConfigKey = "routerName"
RouterNameConfigKey is the optional key that is being registered by router adaptor. It's not as a static field because it's optionally setted, it depends of the router adaptor's author. Usage: app.Config.Other[iris.RouterNameConfigKey]
const (
// Version is the current version number of the Iris web framework
Version = "6.2.0"
)
Variables ¶
var ( // OptionVHost is the addr or the domain that server listens to, which it's optional // When to set VHost manually: // 1. it's automatically setted when you're calling // $instance.Listen/ListenUNIX/ListenTLS/ListenLETSENCRYPT functions or // ln,_ := iris.TCP4/UNIX/TLS/LETSENCRYPT; $instance.Serve(ln) // 2. If you using a balancer, or something like nginx // then set it in order to have the correct url // when calling the template helper '{{url }}' // *keep note that you can use {{urlpath }}) instead* // // Note: this is the main's server Host, you can setup unlimited number of net/http servers // listening to the $instance.Handler after the manually-called $instance.Build // // Default comes from iris.Default.Listen/.Serve with iris' listeners (iris.TCP4/UNIX/TLS/LETSENCRYPT). OptionVHost = func(val string) OptionSet { return func(c *Configuration) { c.VHost = val } } // OptionVScheme is the scheme (http:// or https://) putted at the template function '{{url }}' // It's an optional field, // When to set Scheme manually: // 1. You didn't start the main server using $instance.Listen/ListenTLS/ListenLETSENCRYPT // or $instance.Serve($instance.TCP4()/.TLS...) // 2. if you're using something like nginx and have iris listening with // addr only(http://) but the nginx mapper is listening to https:// // // Default comes from iris.Default.Listen/.Serve with iris' listeners (TCP4,UNIX,TLS,LETSENCRYPT). OptionVScheme = func(val string) OptionSet { return func(c *Configuration) { c.VScheme = val } } // OptionReadTimeout sets the Maximum duration before timing out read of the request. OptionReadTimeout = func(val time.Duration) OptionSet { return func(c *Configuration) { c.ReadTimeout = val } } // OptionWriteTimeout sets the Maximum duration before timing out write of the response. OptionWriteTimeout = func(val time.Duration) OptionSet { return func(c *Configuration) { c.WriteTimeout = val } } // MaxHeaderBytes controls the maximum number of bytes the // server will read parsing the request header's keys and // values, including the request line. It does not limit the // size of the request body. // If zero, DefaultMaxHeaderBytes(8MB) is used. OptionMaxHeaderBytes = func(val int) OptionSet { return func(c *Configuration) { c.MaxHeaderBytes = val } } // OptionCheckForUpdates will try to search for newer version of Iris based on the https://github.com/kataras/iris/releases // If a newer version found then the app will ask the he dev/user if want to update the 'x' version // if 'y' is pressed then the updater will try to install the latest version // the updater, will notify the dev/user that the update is finished and should restart the App manually. // Notes: // 1. Experimental feature // 2. If setted to true, the app will have a little startup delay // 3. If you as developer edited the $GOPATH/src/github/kataras or any other Iris' Go dependencies at the past // then the update process will fail. // // Usage: iris.Default.Set(iris.OptionCheckForUpdates(true)) or // iris.Default.Config.CheckForUpdates = true or // app := iris.New(iris.OptionCheckForUpdates(true)) // Defaults to false. OptionCheckForUpdates = func(val bool) OptionSet { return func(c *Configuration) { c.CheckForUpdates = val } } // OptionDisablePathCorrection 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, // (permant)redirects the client to the correct path /home // // Defaults to false. OptionDisablePathCorrection = func(val bool) OptionSet { return func(c *Configuration) { c.DisablePathCorrection = val } } // OptionEnablePathEscape when is true then its escapes the path, the named path parameters (if any). OptionEnablePathEscape = func(val bool) OptionSet { return func(c *Configuration) { c.EnablePathEscape = val } } // FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) // and fires the 405 error instead of 404 // Defaults to false. OptionFireMethodNotAllowed = func(val bool) OptionSet { return func(c *Configuration) { c.FireMethodNotAllowed = val } } // OptionDisableBodyConsumptionOnUnmarshal manages the reading behavior of the context's body readers/binders. // If setted to true then it // disables the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML`. // // By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`, // if this field setted to true then a new buffer will be created to read from and the request body. // The body will not be changed and existing data before the context.UnmarshalBody/ReadJSON/ReadXML will be not consumed. OptionDisableBodyConsumptionOnUnmarshal = func(val bool) OptionSet { return func(c *Configuration) { c.DisableBodyConsumptionOnUnmarshal = val } } // OptionTimeFormat time format for any kind of datetime parsing. // Defaults to "Mon, 02 Jan 2006 15:04:05 GMT". OptionTimeFormat = func(val string) OptionSet { return func(c *Configuration) { c.TimeFormat = val } } // OptionCharset character encoding for various rendering // used for templates and the rest of the responses // Defaults to "UTF-8". OptionCharset = func(val string) OptionSet { return func(c *Configuration) { c.Charset = val } } // OptionGzip enables gzip compression on your Render actions, this includes any type of render, templates and pure/raw content // If you don't want to enable it globally, you could just use the third parameter on context.Render("myfileOrResponse", structBinding{}, iris.RenderOptions{"gzip": true}) // Defaults to false. OptionGzip = func(val bool) OptionSet { return func(c *Configuration) { c.Gzip = val } } // Other are the custom, dynamic options, can be empty. // This field used only by you to set any app's options you want // or by custom adaptors, it's a way to simple communicate between your adaptors (if any) // Defaults to a non-nil empty map. OptionOther = func(key string, val interface{}) OptionSet { return func(c *Configuration) { if c.Other == nil { c.Other = make(map[string]interface{}, 0) } c.Other[key] = val } } )
All options starts with "Option" preffix in order to be easier to find what dev searching for
var ( // DefaultTimeFormat default time format for any kind of datetime parsing DefaultTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // StaticCacheDuration expiration duration for INACTIVE file handlers, it's a global configuration field to all iris instances StaticCacheDuration = 20 * time.Second )
var ( TranslateLanguageContextKey = "language" TranslateFunctionContextKey = "translate" )
TranslateLanguageContextKey & TranslateFunctionContextKey are used by i18n handlers/middleware currently we have only one: https://github.com/iris-contrib/middleware/tree/master/i18n but you can use these keys to override the i18n's cookie name (TranslateLanguageContextKey) or to store new translate function by using the ctx.Set(iris.TranslateFunctionContextKey, theTrFunc)
var ( // AllMethods contains all the http valid methods: // "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE" AllMethods = [...]string{ MethodGet, MethodPost, MethodPut, MethodDelete, MethodConnect, MethodHead, MethodPatch, MethodOptions, MethodTrace, } )
var ( // DefaultServerAddr the default server addr which is: 0.0.0.0:8080 DefaultServerAddr = DefaultServerHostname + ":" + strconv.Itoa(DefaultServerPort) )
var ErrPushNotSupported = errors.New("push feature is not supported by this ResponseWriter")
ErrPushNotSupported is returned by the Push method to indicate that HTTP/2 Push support is not available.
var LimitRequestBodySize = func(maxRequestBodySizeBytes int64) HandlerFunc { return func(ctx *Context) { ctx.SetMaxRequestBodySize(maxRequestBodySizeBytes) ctx.Next() } }
LimitRequestBodySize is a middleware which sets a request body size limit for all next handlers should be registered before all other handlers
var ProxyHandler = func(redirectSchemeAndHost string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { redirectTo := redirectSchemeAndHost fakehost := r.URL.Host path := r.URL.EscapedPath() if strings.Count(fakehost, ".") >= 3 { if sufIdx := strings.LastIndexByte(fakehost, '.'); sufIdx > 0 { if _, err := strconv.Atoi(fakehost[sufIdx+1:]); err != nil { redirectScheme := ParseScheme(redirectSchemeAndHost) realHost := strings.Replace(redirectSchemeAndHost, redirectScheme, "", 1) redirectHost := strings.Replace(fakehost, fakehost, realHost, 1) redirectTo = redirectScheme + redirectHost + path http.Redirect(w, r, redirectTo, StatusMovedPermanently) return } } } if path != "/" { redirectTo += path } if redirectTo == r.URL.String() { return } http.Redirect(w, r, redirectTo, StatusMovedPermanently) } }
ProxyHandler returns a new net/http.Handler which works as 'proxy', maybe doesn't suits you look its code before using that in production
var Recorder = HandlerFunc(func(ctx *Context) {
ctx.Record()
ctx.Next()
})
Recorder the middleware to enable response writer recording ( *responseWriter -> *ResponseRecorder)
var RequestTransactionScope = TransactionScopeFunc(func(maybeErr TransactionErrResult, ctx *Context) bool { if maybeErr.IsFailure() { ctx.ResponseWriter.SetBeforeFlush(func() { w := ctx.ResponseWriter.(*ResponseRecorder) if maybeErr.Reason != "" { w.SetBodyString(maybeErr.Reason) w.WriteHeader(maybeErr.StatusCode) w.SetContentType(maybeErr.ContentType) } else { ctx.EmitError(maybeErr.StatusCode) } }) return false } return true })
RequestTransactionScope explanation:
if scope fails (if transaction.IsFailure() == true) then the rest of the context's response (transaction or normal flow) is not written to the client, and an error status code is written instead.
var TransientTransactionScope = TransactionScopeFunc(func(maybeErr TransactionErrResult, ctx *Context) bool { if maybeErr.IsFailure() { ctx.Recorder().Reset() } return true })
TransientTransactionScope explanation:
independent 'silent' scope, if transaction fails (if transaction.IsFailure() == true) then its response is not written to the real context no error is provided to the user. useful for the most cases.
Functions ¶
func CERT ¶
CERT returns a listener which contans tls.Config with the provided certificate, use for ssl
func CheckForUpdates ¶
func CheckForUpdates(force bool)
CheckForUpdates will try to search for newer version of Iris based on the https://github.com/kataras/iris/releases If a newer version found then the app will ask the he dev/user if want to update the 'x' version if 'y' is pressed then the updater will try to install the latest version the updater, will notify the dev/user that the update is finished and should restart the App manually. Note: exported func CheckForUpdates exists because of the reason that an update can be executed while Iris is running
func DecodeQuery ¶
DecodeQuery returns the uri parameter as url (string) useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm it uses just the url.QueryUnescape
func DecodeURL ¶
DecodeURL returns the decoded uri useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm it uses just the url.Parse
func LETSENCRYPT ¶
LETSENCRYPT returns a new Automatic TLS Listener using letsencrypt.org service receives three parameters, the first is the host of the server, second can be the server name(domain) or empty if skip verification is the expected behavior (not recommended) and the third is optionally, the cache directory, if you skip it then the cache directory is "./certcache" if you want to disable cache directory then simple give it a value of empty string ""
does NOT supports localhost domains for testing.
this is the recommended function to use when you're ready for production state
func ParseHost ¶
ParseHost tries to convert a given string to an address which is compatible with net.Listener and server
func ParseHostname ¶
ParseHostname receives an addr of form host[:port] and returns the hostname part of it ex: localhost:8080 will return the `localhost`, mydomain.com:8080 will return the 'mydomain'
func ParsePort ¶
ParsePort receives an addr of form host[:port] and returns the port part of it ex: localhost:8080 will return the `8080`, mydomain.com will return the '80'
func ParseScheme ¶
ParseScheme returns the scheme based on the host,addr,domain Note: the full scheme not just http*,https* *http:// *https://
func Proxy ¶
Proxy not really a proxy, it's just starts a server listening on proxyAddr but redirects all requests to the redirectToSchemeAndHost+$path nothing special, use it only when you want to start a secondary server which its only work is to redirect from one requested path to another
returns a close function
func RouteConflicts ¶
RouteConflicts checks for route's middleware conflicts
func StatusText ¶
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
func TCPKeepAlive ¶
TCPKeepAlive returns a new tcp4 keep alive Listener
func ToNativeHandler ¶
ToNativeHandler converts an iris handler to http.Handler
Types ¶
type BodyDecoder ¶
BodyDecoder is an interface which any struct can implement in order to customize the decode action from ReadJSON and ReadXML
Trivial example of this could be: type User struct { Username string }
func (u *User) Decode(data []byte) error { return json.Unmarshal(data, u) }
the 'context.ReadJSON/ReadXML(&User{})' will call the User's Decode option to decode the request body
Note: This is totally optionally, the default decoders for ReadJSON is the encoding/json and for ReadXML is the encoding/xml
type Configuration ¶
type Configuration struct { // VHost is the addr or the domain that server listens to, which it's optional // When to set VHost manually: // 1. it's automatically setted when you're calling // $instance.Listen/ListenUNIX/ListenTLS/ListenLETSENCRYPT functions or // ln,_ := iris.TCP4/UNIX/TLS/LETSENCRYPT; $instance.Serve(ln) // 2. If you using a balancer, or something like nginx // then set it in order to have the correct url // when calling the template helper '{{url }}' // *keep note that you can use {{urlpath }}) instead* // // Note: this is the main's server Host, you can setup unlimited number of net/http servers // listening to the $instance.Handler after the manually-called $instance.Build // // Default comes from iris.Default.Listen/.Serve with iris' listeners (iris.TCP4/UNIX/TLS/LETSENCRYPT). VHost string `yaml:"VHost"` // VScheme is the scheme (http:// or https://) putted at the template function '{{url }}' // It's an optional field, // When to set VScheme manually: // 1. You didn't start the main server using $instance.Listen/ListenTLS/ListenLETSENCRYPT // or $instance.Serve($instance.TCP4()/.TLS...) // 2. if you're using something like nginx and have iris listening with // addr only(http://) but the nginx mapper is listening to https:// // // Default comes from iris.Default.Listen/.Serve with iris' listeners (TCP4,UNIX,TLS,LETSENCRYPT). VScheme string `yaml:"VScheme" toml:"VScheme"` // ReadTimeout is the maximum duration before timing out read of the request. ReadTimeout time.Duration `yaml:"ReadTimeout" toml:"ReadTimeout"` // WriteTimeout is the maximum duration before timing out write of the response. WriteTimeout time.Duration `yaml:"WriteTimeout" toml:"WriteTimeout"` // MaxHeaderBytes controls the maximum number of bytes the // server will read parsing the request header's keys and // values, including the request line. It does not limit the // size of the request body. // If zero, DefaultMaxHeaderBytes is used. MaxHeaderBytes int `yaml:"MaxHeaderBytes" toml:"MaxHeaderBytes"` // CheckForUpdates will try to search for newer version of Iris based on the https://github.com/kataras/iris/releases // If a newer version found then the app will ask the he dev/user if want to update the 'x' version // if 'y' is pressed then the updater will try to install the latest version // the updater, will notify the dev/user that the update is finished and should restart the App manually. // Notes: // 1. Experimental feature // 2. If setted to true, the app will start the server normally and runs the updater in its own goroutine, // in order to no delay the boot time on your development state. // 3. If you as developer edited the $GOPATH/src/github/kataras or any other Iris' Go dependencies at the past // then the update process will fail. // // Usage: app := iris.New(iris.Configuration{CheckForUpdates: true}) // // Defaults to false. CheckForUpdates bool `yaml:"CheckForUpdates" toml:"CheckForUpdates"` // 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, // (permant)redirects the client to the correct path /home // // Defaults to false. DisablePathCorrection bool `yaml:"DisablePathCorrection" toml:"DisablePathCorrection"` // EnablePathEscape when is true then its escapes the path, the named parameters (if any). // Change to false it if you want something like this https://github.com/kataras/iris/issues/135 to work // // When do you need to Disable(false) it: // accepts parameters with slash '/' // Request: http://localhost:8080/details/Project%2FDelta // ctx.Param("project") returns the raw named parameter: Project%2FDelta // which you can escape it manually with net/url: // projectName, _ := url.QueryUnescape(c.Param("project"). // // Defaults to false. EnablePathEscape bool `yaml:"EnablePathEscape" toml:"EnablePathEscape"` // FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) and // fires the 405 error instead of 404 // Defaults to false. FireMethodNotAllowed bool `yaml:"FireMethodNotAllowed" toml:"FireMethodNotAllowed"` // DisableBodyConsumptionOnUnmarshal manages the reading behavior of the context's body readers/binders. // If setted to true then it // disables the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML`. // // By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`, // if this field setted to true then a new buffer will be created to read from and the request body. // The body will not be changed and existing data before the // context.UnmarshalBody/ReadJSON/ReadXML will be not consumed. DisableBodyConsumptionOnUnmarshal bool `yaml:"DisableBodyConsumptionOnUnmarshal" toml:"DisableBodyConsumptionOnUnmarshal"` // TimeFormat time format for any kind of datetime parsing // Defaults to "Mon, 02 Jan 2006 15:04:05 GMT". TimeFormat string `yaml:"TimeFormat" toml:"TimeFormat"` // Charset character encoding for various rendering // used for templates and the rest of the responses // Defaults to "UTF-8". Charset string `yaml:"Charset" toml:"Charset"` // Gzip enables gzip compression on your Render actions, this includes any type of render, // templates and pure/raw content // If you don't want to enable it globally, you could just use the third parameter // on context.Render("myfileOrResponse", structBinding{}, iris.RenderOptions{"gzip": true}) // Defaults to false. Gzip bool `yaml:"Gzip" toml:"Gzip"` // Other are the custom, dynamic options, can be empty. // This field used only by you to set any app's options you want // or by custom adaptors, it's a way to simple communicate between your adaptors (if any) // Defaults to a non-nil empty map // // Some times is useful to know the router's name in order to take some dynamically runtime decisions. // So, when router policies are being adapted by a router adaptor, // a "routeName" key will be(optionally) filled with the name of the Router's features are being used. // The "routeName" can be retrivied by: // app := iris.New() // app.Adapt(routerAdaptor.New()) // app.Config.Other[iris.RouterNameConfigKey] // Other map[string]interface{} `yaml:"Other" toml:"Other"` }
Configuration the whole configuration for an Iris station instance these can be passed via options also, look at the top of this file(configuration.go). Configuration is a valid OptionSetter.
func DefaultConfiguration ¶
func DefaultConfiguration() Configuration
DefaultConfiguration returns the default configuration for an Iris station, fills the main Configuration
func TOML ¶
func TOML(filename string) Configuration
TOML reads Configuration from a toml-compatible document file. Read more about toml's implementation at: https://github.com/toml-lang/toml
Accepts the absolute path of the configuration file. An error will be shown to the user via panic with the error message. Error may occur when the file doesn't exists or is not formatted correctly.
Usage: 1. `app := iris.New(iris.TOML("myconfig.toml"))` or 2. `app.Set(iris.TOML("myconfig.toml"))`
func YAML ¶
func YAML(filename string) Configuration
YAML reads Configuration from a configuration.yml file.
Accepts the absolute path of the configuration.yml. An error will be shown to the user via panic with the error message. Error may occur when the configuration.yml doesn't exists or is not formatted correctly.
Usage: 1. `app := iris.New(iris.YAML("myconfig.yml"))` or 2. `app.Set(iris.YAML("myconfig.yml"))`
func (Configuration) Set ¶
func (c Configuration) Set(main *Configuration)
Set implements the OptionSetter
type Context ¶
type Context struct { ResponseWriter // *responseWriter by default, when record is on then *ResponseRecorder Request *http.Request //keep track all registered middleware (handlers) Middleware Middleware // exported because is useful for debugging // Pos is the position number of the Context, look .Next to understand Pos int // exported because is useful for debugging // contains filtered or unexported fields }
Context is the "midle-man"" server's object for the clients.
A New Context is being acquired from a sync.Pool on each connection. The Context is the most important thing on the Iris' http flow.
Developers send responses to the client's request through a Context. Developers get request information from the client's request a Context.
func (*Context) BeginTransaction ¶
func (ctx *Context) BeginTransaction(pipe func(transaction *Transaction))
BeginTransaction starts a scoped transaction.
Can't say a lot here because it will take more than 200 lines to write about. You can search third-party articles or books on how Business Transaction works (it's quite simple, especially here).
Note that this is unique and new (=I haver never seen any other examples or code in Golang on this subject, so far, as with the most of iris features...) it's not covers all paths, such as databases, this should be managed by the libraries you use to make your database connection, this transaction scope is only for context's response. Transactions have their own middleware ecosystem also, look iris.go:UseTransaction.
See https://github.com/iris-contrib/examples/tree/master/transactions for more
func (*Context) Data ¶
Data writes out the raw bytes as binary data.
RenderPolicy does NOT apply to context.HTML, context.Text and context.Data To change their default behavior users should use the context.RenderWithStatus(statusCode, contentType, content, options...) instead.
func (*Context) Deadline ¶
Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.
func (*Context) Do ¶
func (ctx *Context) Do()
Do calls the first handler only, it's like Next with negative pos, used only on Router&MemoryRouter
func (*Context) Done ¶
func (ctx *Context) Done() <-chan struct{}
Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value.
WithCancel arranges for Done to be closed when cancel is called; WithDeadline arranges for Done to be closed when the deadline expires; WithTimeout arranges for Done to be closed when the timeout elapses.
Done is provided for use in select statements:
// Stream generates values with DoSomething and sends them to out // until DoSomething returns an error or ctx.Done is closed. func Stream(ctx context.Context, out chan<- Value) error { for { v, err := DoSomething(ctx) if err != nil { return err } select { case <-ctx.Done(): return ctx.Err() case out <- v: } } }
See http://blog.golang.org/pipelines for more examples of how to use a Done channel for cancelation.
func (*Context) EmitError ¶
EmitError executes the custom error by the http status code passed to the function
func (*Context) Err ¶
Err returns a non-nil error value after Done is closed. Err returns Canceled if the context was canceled or DeadlineExceeded if the context's deadline passed. No other values for Err are defined. After Done is closed, successive calls to Err return the same value.
func (*Context) ExecRoute ¶
ExecRoute calls any route (mostly "offline" route) like it was requested by the user, but it is not. Offline means that the route is registered to the iris and have all features that a normal route has BUT it isn't available by browsing, its handlers executed only when other handler's context call them it can validate paths, has sessions, path parameters and all.
You can find the Route by iris.Default.Routes().Lookup("theRouteName") you can set a route name as: myRoute := iris.Default.Get("/mypath", handler)("theRouteName") that will set a name to the route and returns its iris.Route instance for further usage.
It doesn't changes the global state, if a route was "offline" it remains offline.
see ExecRouteAgainst(routeName, againstRequestPath string), iris.Default.None(...) and iris.Default.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585
Example: https://github.com/iris-contrib/examples/tree/master/route_state
func (*Context) ExecRouteAgainst ¶
ExecRouteAgainst calls any iris.Route against a 'virtually' request path like it was requested by the user, but it is not. Offline means that the route is registered to the iris and have all features that a normal route has BUT it isn't available by browsing, its handlers executed only when other handler's context call them it can validate paths, has sessions, path parameters and all.
You can find the Route by iris.Default.Routes().Lookup("theRouteName") you can set a route name as: myRoute := iris.Default.Get("/mypath", handler)("theRouteName") that will set a name to the route and returns its iris.Route instance for further usage.
It doesn't changes the global state, if a route was "offline" it remains offline.
see ExecRoute(routeName), iris.Default.None(...) and iris.Default.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585
Example: https://github.com/iris-contrib/examples/tree/master/route_state
User can get the response by simple using rec := ctx.Recorder(); rec.Body()/rec.StatusCode()/rec.Header() The route will be executed via the Router, as it would requested by client.
func (*Context) FormFile ¶
FormFile returns the first file for the provided form key. FormFile calls ctx.Request.ParseMultipartForm and ParseForm if necessary.
same as Request.FormFile
func (*Context) FormValues ¶
FormValues returns all post data values with their keys form data, get, post & put query arguments
NOTE: A check for nil is necessary for zero results
func (*Context) Framework ¶
Framework returns the Iris instance, containing the configuration and all other fields
func (*Context) GetCookie ¶
GetCookie returns cookie's value by it's name returns empty string if nothing was found
func (*Context) GetHandlerName ¶
GetHandlerName as requested returns the stack-name of the function which the Middleware is setted from
func (*Context) GetInt ¶
GetInt same as Get but tries to convert the return value as integer if nothing found or canno be parsed to integer it returns an error
func (*Context) GetString ¶
GetString same as Get but returns the value as string if nothing founds returns empty string ""
func (*Context) HTML ¶
HTML writes html string with a http status
RenderPolicy does NOT apply to context.HTML, context.Text and context.Data To change their default behavior users should use the context.RenderWithStatus(statusCode, contentType, content, options...) instead.
func (*Context) IsAjax ¶
IsAjax returns true if this request is an 'ajax request'( XMLHttpRequest)
Read more at: http://www.w3schools.com/ajax/
func (*Context) IsRecording ¶
func (ctx *Context) IsRecording() (*ResponseRecorder, bool)
IsRecording returns the response recorder and a true value when the response writer is recording the status code, body, headers and so on, else returns nil and false
func (*Context) IsStopped ¶
IsStopped checks and returns true if the current position of the Context is 255, means that the StopExecution has called
func (*Context) Markdown ¶
Markdown parses and renders to the client a particular (dynamic) markdown string accepts two parameters first is the http status code second is the markdown string
func (*Context) MarkdownString ¶
MarkdownString parses the (dynamic) markdown string and returns the converted html string
func (*Context) MaxAge ¶
MaxAge returns the "cache-control" request header's value seconds as int64 if header not found or parse failed then it returns -1
func (*Context) MustRender ¶
MustRender same as .Render but returns 503 service unavailable http status with a (html) message if render failed Note: the options: "gzip" and "charset" are built'n support by Iris, so you can pass these on any template engine or serialize engine.
Look: .ViewData | .Render
.ViewLayout | .RenderWithStatus also.
Examples: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/
func (*Context) Next ¶
func (ctx *Context) Next()
Next calls all the next handler from the middleware stack, it used inside a middleware
func (*Context) NextHandler ¶
NextHandler returns the next handler in the chain (ctx.Middleware) otherwise nil. Notes:
If the result of NextHandler() will be executed then the ctx.Pos (which is exported for these reasons) should be manually increment(++) otherwise your app will visit twice the same handler.
func (*Context) NotFound ¶
func (ctx *Context) NotFound()
NotFound emits an error 404 to the client, using the custom http errors if no custom errors provided then it sends the default error message
func (*Context) Panic ¶
func (ctx *Context) Panic()
Panic emits an error 500 to the client, using the custom http errors if no custom errors rpovided then it sends the default error message
func (*Context) Param ¶
Param returns the string representation of the key's path named parameter's value same as GetString
func (*Context) ParamDecoded ¶
ParamDecoded returns a url-query-decoded path parameter's value
func (*Context) ParamInt ¶
ParamInt returns the int representation of the key's path named parameter's value same as GetInt
func (*Context) ParamInt64 ¶
ParamInt64 returns the int64 representation of the key's path named parameter's value
func (*Context) ParamIntWildcard ¶
ParamIntWildcard removes the first slash if found and returns the int representation of the key's wildcard path parameter's value.
Returns -1 with an error if the parameter couldn't be found.
func (*Context) ParamValidate ¶
ParamValidate receives a compiled Regexp and execute a parameter's value against this regexp, returns true if matched or param not found, otherwise false.
It accepts a compiled regexp to reduce the performance cost on serve time. If you need a more automative solution, use the `app.Regex` or `app.RegexSingle` instead.
This function helper is ridiculous simple but it's good to have it on one place.
func (*Context) ParamsLen ¶
ParamsLen tries to return all the stored values which values are string, probably most of them will be the path parameters
func (*Context) ParamsSentence ¶
ParamsSentence returns a string implementation of all parameters that this context keeps hasthe form of key1=value1,key2=value2...
func (*Context) Path ¶
Path returns the full escaped path as string for unescaped use: ctx.RequestCtx.RequestURI() or RequestPath(escape bool)
func (*Context) PostValue ¶
PostValue returns a form's only-post value by its name same as Request.PostFormValue
func (*Context) ReadForm ¶
ReadForm binds the formObject with the form data it supports any kind of struct
func (*Context) ReadJSON ¶
ReadJSON reads JSON from request's body and binds it to a value of any json-valid type
func (*Context) ReadXML ¶
ReadXML reads XML from request's body and binds it to a value of any xml-valid type
func (*Context) Record ¶
func (ctx *Context) Record()
Record transforms the context's basic and direct responseWriter to a ResponseRecorder which can be used to reset the body, reset headers, get the body, get & set the status code at any time and more
func (*Context) Recorder ¶
func (ctx *Context) Recorder() *ResponseRecorder
Recorder returns the context's ResponseRecorder if not recording then it starts recording and returns the new context's ResponseRecorder
func (*Context) Redirect ¶
Redirect redirect sends a redirect response the client accepts 2 parameters string and an optional int first parameter is the url to redirect second parameter is the http status should send, default is 302 (StatusFound), you can set it to 301 (Permant redirect), if that's nessecery
func (*Context) RedirectTo ¶
RedirectTo does the same thing as Redirect but instead of receiving a uri or path it receives a route name
func (*Context) RemoteAddr ¶
RemoteAddr tries to return the real client's request IP
func (*Context) RemoveCookie ¶
RemoveCookie deletes a cookie by it's name/key
func (*Context) Render ¶
func (ctx *Context) Render(name string, binding interface{}, options ...map[string]interface{}) error
Render same as .RenderWithStatus but with status to iris.StatusOK (200) if no previous status exists builds up the response from the specified template or a serialize engine. Note: the options: "gzip" and "charset" are built'n support by Iris, so you can pass these on any template engine or serialize engine.
Look: .ViewData | .MustRender
.ViewLayout | .RenderWithStatus also.
Examples: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/
func (*Context) RenderWithStatus ¶
func (ctx *Context) RenderWithStatus(status int, name string, binding interface{}, options ...map[string]interface{}) (err error)
RenderWithStatus builds up the response from the specified template or a serialize engine. Note: the options: "gzip" and "charset" are built'n support by Iris, so you can pass these on any template engine or serialize engines.
Look: .ViewData | .Render
.ViewLayout | .MustRender also.
Examples: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/
func (*Context) RequestHeader ¶
RequestHeader returns the request header's value accepts one parameter, the key of the header (string) returns string
func (*Context) RequestPath ¶
RequestPath returns the requested path
func (*Context) SendFile ¶
SendFile sends file for force-download to the client
Use this instead of ServeFile to 'force-download' bigger files to the client
func (*Context) ServeContent ¶
func (ctx *Context) ServeContent(content io.ReadSeeker, filename string, modtime time.Time, gzipCompression bool) error
ServeContent serves content, headers are autoset receives three parameters, it's low-level function, instead you can use .ServeFile(string,bool)/SendFile(string,string)
You can define your own "Content-Type" header also, after this function call Doesn't implements resuming (by range), use ctx.SendFile instead
func (*Context) ServeFile ¶
ServeFile serves a view file, to send a file ( zip for example) to the client you should use the SendFile(serverfilename,clientfilename) receives two parameters filename/path (string) gzipCompression (bool)
You can define your own "Content-Type" header also, after this function call This function doesn't implement resuming (by range), use ctx.SendFile instead
Use it when you want to serve css/js/... files to the client, for bigger files and 'force-download' use the SendFile
func (*Context) ServerHost ¶
ServerHost returns the server host taken by *http.Request.Host
func (*Context) Session ¶
Session returns the current Session.
if SessionsPolicy is missing then a detailed how-to-fix message will be visible to the user (DevMode) and the return value will be NILL.
func (*Context) SessionDestroy ¶
func (ctx *Context) SessionDestroy()
SessionDestroy destroys the whole session, calls the provider's destroy and remove the cookie
func (*Context) SetClientCachedBody ¶
func (ctx *Context) SetClientCachedBody(status int, bodyContent []byte, cType string, modtime time.Time) error
SetClientCachedBody like SetBody but it sends with an expiration datetime which is managed by the client-side (all major browsers supports this feature)
func (*Context) SetContentType ¶
SetContentType sets the response writer's header key 'Content-Type' to a given value(s)
func (*Context) SetCookieKV ¶
SetCookieKV adds a cookie, receives just a key(string) and a value(string)
Expires on 2 hours by default(unchable) use ctx.SetCookie or http.SetCookie instead for more control.
func (*Context) SetHeader ¶
SetHeader write to the response writer's header to a given key the given value
func (*Context) SetMaxRequestBodySize ¶
SetMaxRequestBodySize sets a limit to the request body size should be called before reading the request body from the client
func (*Context) SetStatusCode ¶
SetStatusCode sets the status code header to the response
same as .WriteHeader, iris takes cares of your status code seriously
func (*Context) SkipTransactions ¶
func (ctx *Context) SkipTransactions()
SkipTransactions if called then skip the rest of the transactions or all of them if called before the first transaction
func (*Context) StopExecution ¶
func (ctx *Context) StopExecution()
StopExecution just sets the .pos to 255 in order to not move to the next middlewares(if any)
func (*Context) StreamWriter ¶
StreamWriter registers the given stream writer for populating response body.
Access to context's and/or its' members is forbidden from writer.
This function may be used in the following cases:
- if response body is too big (more than iris.LimitRequestBodySize(if setted)).
- if response body is streamed from slow external sources.
- if response body must be streamed to the client in chunks. (aka `http server push`).
receives a function which receives the response writer and returns false when it should stop writing, otherwise true in order to continue
func (*Context) Text ¶
Text writes out a string as plain text.
RenderPolicy does NOT apply to context.HTML, context.Text and context.Data To change their default behavior users should use the context.RenderWithStatus(statusCode, contentType, content, options...) instead.
func (*Context) TransactionsSkipped ¶
TransactionsSkipped returns true if the transactions skipped or canceled at all.
func (*Context) Translate ¶
Translate is the i18n (localization) middleware's function, it just calls the ctx.getFmt("translate"). "translate" is the key of the i18n middlweare for more plaese look: https://github.com/iris-contrib/examples/tree/master/middleware_internationalization_i18n
func (*Context) TryWriteGzip ¶
TryWriteGzip accepts bytes, which are compressed to gzip format and sent to the client. If client does not supprots gzip then the contents are written as they are, uncompressed.
func (*Context) URLParamInt ¶
URLParamInt returns the url query parameter as int value from a request , returns error on parse fail
func (*Context) URLParamInt64 ¶
URLParamInt64 returns the url query parameter as int64 value from a request , returns error on parse fail
func (*Context) URLParams ¶
URLParams returns a map of GET query parameters separated by comma if more than one it returns an empty map if nothing founds
func (*Context) URLParamsAsMulti ¶
URLParamsAsMulti returns a map of list contains the url get parameters
func (*Context) UnmarshalBody ¶
func (ctx *Context) UnmarshalBody(v interface{}, unmarshaler Unmarshaler) error
UnmarshalBody reads the request's body and binds it to a value or pointer of any type Examples of usage: context.ReadJSON, context.ReadXML
func (*Context) Value ¶
func (ctx *Context) Value(key interface{}) interface{}
Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.
Use context values only for request-scoped data that transits processes and API boundaries, not for passing optional parameters to functions.
A key identifies a specific value in a Context. Functions that wish to store values in Context typically allocate a key in a global variable then use that key as the argument to context.WithValue and Context.Value. A key can be any type that supports equality; packages should define keys as an unexported type to avoid collisions.
Packages that define a Context key should provide type-safe accessors for the values stores using that key:
// Package user defines a User type that's stored in Contexts. package user import "golang.org/x/net/context" // User is the type of value stored in the Contexts. type User struct {...} // key is an unexported type for keys defined in this package. // This prevents collisions with keys defined in other packages. type key int // userKey is the key for user.User values in Contexts. It is // unexported; clients use user.NewContext and user.FromContext // instead of using this key directly. var userKey key = 0 // NewContext returns a new Context that carries value u. func NewContext(ctx context.Context, u *User) context.Context { return context.WithValue(ctx, userKey, u) } // FromContext returns the User value stored in ctx, if any. func FromContext(ctx context.Context) (*User, bool) { u, ok := ctx.Value(userKey).(*User) return u, ok }
func (*Context) ValuesLen ¶
ValuesLen returns the total length of the user values storage, some of them maybe path parameters
func (*Context) ViewData ¶
ViewData saves one or more key-value pair in order to be passed if and when .Render is being called afterwards, in the same request. Useful when need to set or/and change template data from previous hanadlers in the chain.
If .Render's "binding" argument is not nil and it's not a type of map then these data are being ignored, binding has the priority, so the main route's handler can still decide. If binding is a map or iris.Map then theese data are being added to the view data and passed to the template.
After .Render, the data are not destroyed, in order to be re-used if needed (again, in the same request as everything else), to manually clear the view data, developers can call: ctx.Set(iris.ViewDataContextKey, iris.Map{})
Look: .ViewLayout | .Render
.MustRender | .RenderWithStatus also.
Example: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/context-view-data/
func (*Context) ViewLayout ¶
ViewLayout sets the "layout" option if and when .Render is being called afterwards, in the same request. Useful when need to set or/and change a layout based on the previous handlers in the chain.
Look: .ViewData | .Render
.MustRender | .RenderWithStatus also.
Example: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/context-view-data/
func (*Context) VirtualHostname ¶
VirtualHostname returns the hostname that user registers, host path maybe differs from the real which is the Host(), which taken from a net.listener
func (*Context) VisitAllCookies ¶
VisitAllCookies takes a visitor which loops on each (request's) cookie key and value
func (*Context) VisitValues ¶
VisitValues calls visitor for each existing context's temp values.
visitor must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning.
type ContextPool ¶
type ContextPool interface { // Acquire returns a Context from pool. // See Release. Acquire(w http.ResponseWriter, r *http.Request) *Context // Release puts a Context back to its pull, this function releases its resources. // See Acquire. Release(ctx *Context) // Framework is never used, except when you're in a place where you don't have access to the *iris.Framework station // but you need to fire a func or check its Config. // // Used mostly inside external routers to take the .Config.VHost // without the need of other param receivers and refactors when changes // // note: we could make a variable inside contextPool which would be received by newContextPool // but really doesn't need, we just need to borrow a context: we are in pre-build state // so the server is not actually running yet, no runtime performance cost. Framework() *Framework // Run is a combination of Acquire and Release , between these two the `runner` runs, // when `runner` finishes its job then the Context is being released. Run(w http.ResponseWriter, r *http.Request, runner func(ctx *Context)) }
ContextPool is a set of temporary *Context that may be individually saved and retrieved.
Any item stored in the Pool may be removed automatically at any time without notification. If the Pool holds the only reference when this happens, the item might be deallocated.
The ContextPool is safe for use by multiple goroutines simultaneously.
ContextPool's purpose is to cache allocated but unused Contexts for later reuse, relieving pressure on the garbage collector.
type ErrorHandlers ¶
type ErrorHandlers struct {
// contains filtered or unexported fields
}
ErrorHandlers contains all custom http errors. A custom http error handler is just a handler with its status code.
func (*ErrorHandlers) Fire ¶
func (e *ErrorHandlers) Fire(statusCode int, ctx *Context)
Fire fires an error based on the `statusCode`
func (*ErrorHandlers) Get ¶
func (e *ErrorHandlers) Get(statusCode int) Handler
Get returns the handler which is responsible for this 'statusCode' http error.
func (*ErrorHandlers) GetOrRegister ¶
func (e *ErrorHandlers) GetOrRegister(statusCode int) Handler
GetOrRegister trys to return the handler which is responsible for the 'statusCode', if it was nil then it creates a new one, registers that to the error list and returns that.
func (*ErrorHandlers) Register ¶
func (e *ErrorHandlers) Register(statusCode int, handler Handler)
Register registers a handler to a http status.
func (*ErrorHandlers) RegisterRegex ¶
func (e *ErrorHandlers) RegisterRegex(statusCode int, handler Handler, expr string) error
RegisterRegex same as Register but it receives a third parameter which is the regex expression which is running versus the REQUESTED PATH, i.e "/api/users/42".
If the match against the REQUEST PATH and the 'expr' failed then the previous registered error handler on this specific 'statusCode' will be executed.
Returns an error if regexp.Compile failed, nothing special.
type EventListener ¶
type EventListener func(*Framework)
EventListener is the signature for type of func(*Framework), which is used to register events inside an EventPolicy.
Keep note that, inside the policy this is a wrapper in order to register more than one listener without the need of slice.
type EventPolicy ¶
type EventPolicy struct { // Boot with a listener type of EventListener. // Fires when '.Boot' is called (by .Serve functions or manually), // before the Build of the components and the Listen, // after VHost and VSCheme configuration has been setted. Boot EventListener // Before Listen, after Boot Build EventListener // Interrupted with a listener type of EventListener. // Fires after the terminal is interrupted manually by Ctrl/Cmd + C // which should be used to release external resources. // Iris will close and os.Exit at the end of custom interrupted events. // If you want to prevent the default behavior just block on the custom Interrupted event. Interrupted EventListener // Recover with a listener type of func(*Framework, interface{}). // Fires when an unexpected error(panic) is happening at runtime, // while the server's net.Listener accepting requests // or when a '.Must' call contains a filled error. // Used to release external resources and '.Close' the server. // Only one type of this callback is allowed. // // If not empty then the Framework will skip its internal // server's '.Close' and panic to its '.Logger' and execute that callback instaed. // Differences from Interrupted: // 1. Fires on unexpected errors // 2. Only one listener is allowed. Recover func(*Framework, error) }
EventPolicy contains the available Framework's flow event callbacks. Available events: - Boot - Build - Interrupted - Recover
func (EventPolicy) Adapt ¶
func (e EventPolicy) Adapt(frame *Policies)
Adapt adaps an EventPolicy object to the main *Policies.
func (EventPolicy) Fire ¶
func (e EventPolicy) Fire(ln EventListener, s *Framework) bool
Fire fires an EventListener with its Framework when listener is not nil. Returns true when fired, otherwise false.
type Framework ¶
type Framework struct { // Router is the Router API, REST Routing, Static files & favicon, // Grouping, Custom HTTP Errors, Subdomains and more. // // This field is available before 'Boot' but the routes are actually registered after 'Boot' // if no RouterBuilderPolicy was .Adapt(ed) by user then // it throws a panic with detailed information of how-to-fix it. *Router // Config contains the configuration fields // all fields defaults to something that is working, developers don't have to set it. // // can be setted via .New, .Set and .New(.YAML) Config *Configuration // TLSNextProto optionally specifies a function to take over // ownership of the provided TLS connection when an NPN/ALPN // protocol upgrade has occurred. The map key is the protocol // name negotiated. The Handler argument should be used to // handle HTTP requests and will initialize the Request's TLS // and RemoteAddr if not already set. The connection is // automatically closed when the function returns. // If TLSNextProto is nil, HTTP/2 support is enabled automatically. TLSNextProto map[string]func(*http.Server, *tls.Conn, http.Handler) // same as http.Server.TLSNextProto // ConnState specifies an optional callback function that is // called when a client connection changes state. See the // ConnState type and associated constants for details. ConnState func(net.Conn, http.ConnState) // same as http.Server.ConnState // Shutdown gracefully shuts down the server without interrupting any // active connections. Shutdown works by first closing all open // listeners, then closing all idle connections, and then waiting // indefinitely for connections to return to idle and then shut down. // If the provided context expires before the shutdown is complete, // then the context's error is returned. // // Shutdown does not attempt to close nor wait for hijacked // connections such as WebSockets. The caller of Shutdown should // separately notify such long-lived connections of shutdown and wait // for them to close, if desired. Shutdown func(context.Context) error // contains filtered or unexported fields }
Framework is our God |\| Google.Search('Greek mythology Iris').
var ( Default *Framework // ResetDefault resets the `.Default` // to an empty *Framework with the default configuration. // // Note: ResetDefault field itself can be setted // to custom function too. ResetDefault = func() { Default = New() } )
Default is the field which keeps an empty `Framework` instance with its default configuration (config can change at runtime).
Use that as `iris.Default.Handle(...)` or create a new, ex: `app := iris.New(); app.Handle(...)`
func New ¶
func New(setters ...OptionSetter) *Framework
New creates and returns a fresh Iris *Framework instance with the default configuration if no 'setters' parameters passed.
func (*Framework) Adapt ¶
Adapt adapds a policy to the Framework. It accepts single or more objects that implements the iris.Policy. Iris provides some of them but you can build your own based on one or more of these: - iris.EventPolicy - iris.RouterReversionPolicy - iris.RouterBuilderPolicy - iris.RouterWrapperPolicy - iris.TemplateRenderPolicy - iris.TemplateFuncsPolicy
With a Policy you can change the behavior of almost each of the existing Iris' features. See policy.go for more.
func (*Framework) Boot ¶
Boot runs only once, automatically
when 'Serve/Listen/ListenTLS/ListenUNIX/ListenLETSENCRYPT' called.
It's exported because you may want to build the router
and its components but not run the server.
See ./httptest/httptest.go to understand its usage.
func (*Framework) Cache ¶
func (s *Framework) Cache(bodyHandler HandlerFunc, expiration time.Duration) HandlerFunc
Cache is just a wrapper for a route's handler which you want to enable body caching
Usage: iris.Default.Get("/", iris.Cache(func(ctx *iris.Context){ ctx.WriteString("Hello, world!") // or a template or anything else }, time.Duration(10*time.Second))) // duration of expiration
if <=time.Second then it tries to find it though request header's "cache-control" maxage value
func (*Framework) Listen ¶
Listen starts the standalone http server which listens to the addr parameter which as the form of host:port
If you need to manually monitor any error please use `.Serve` instead.
func (*Framework) ListenLETSENCRYPT ¶
ListenLETSENCRYPT starts a server listening at the specific nat address using key & certification taken from the letsencrypt.org 's servers it's also starts a second 'http' server to redirect all 'http://$ADDR_HOSTNAME:80' to the' https://$ADDR' it creates a cache file to store the certifications, for performance reasons, this file by-default is "./certcache" if you skip the second parameter then the cache file is "./letsencrypt.cache" if you want to disable cache then simple pass as second argument an empty empty string ""
Note: HTTP/2 Push is not working with LETSENCRYPT, you have to use ListenTLS to enable HTTP/2 Because net/http's author didn't exported the functions to tell the server that is using HTTP/2...
example: https://github.com/kataras/iris/blob/v6/_examples/beginner/listen-letsencrypt/main.go
func (*Framework) ListenTLS ¶
ListenTLS Starts a https server with certificates, if you use this method the requests of the form of 'http://' will fail only https:// connections are allowed which listens to the addr parameter which as the form of host:port
If you need to manually monitor any error please use `.Serve` instead.
func (*Framework) ListenUNIX ¶
ListenUNIX starts the process of listening to the new requests using a 'socket file', Note: this works only on unix
If you need to manually monitor any error please use `.Serve` instead.
example: https://github.com/kataras/iris/blob/v6/_examples/beginner/listen-unix/main.go
func (*Framework) Log ¶
Log logs to the defined logger policy.
The default outputs to the os.Stdout when EnvMode is 'iris.ProdMode'
func (*Framework) Must ¶
Must checks if the error is not nil, if it isn't panics on registered iris' logger or to a recovery event handler, otherwise does nothing.
func (*Framework) Path ¶
Path used to check arguments with the route's named parameters and return the correct url if parse failed returns empty string. Used for reverse routing, depends on router adaptor.
Examples: https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_3 (gorillamux) https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_4 (httprouter)
func (*Framework) Regex ¶
func (s *Framework) Regex(pairParamExpr ...string) HandlerFunc
Regex takes pairs with the named path (without symbols) following by its expression and returns a middleware which will do a pure but effective validation using the regexp package.
Note: '/adaptors/gorillamux' already supports regex path validation. It's useful while the developer uses the '/adaptors/httprouter' instead.
func (*Framework) RegexSingle ¶
func (s *Framework) RegexSingle(paramName string, expr string, onFail HandlerFunc) HandlerFunc
func (*Framework) Render ¶
func (s *Framework) Render(w io.Writer, name string, bind interface{}, options ...map[string]interface{}) error
Render renders using the specific template or any other rich content renderer to the 'w'.
Example of usage:
- send an e-mail using a template engine that you already adapted via: app.Adapt(view.HTML("./templates", ".html")) or app.Adapt(iris.RenderPolicy(mycustomRenderer)).
It can also render json,xml,jsonp and markdown by-default before or after .Build too.
func (*Framework) RouteParam ¶
RouteParam returns a named parameter as each router defines named path parameters. For example, with the httprouter(: as named param symbol): userid should return :userid. with gorillamux, userid should return {userid} or userid[1-9]+ should return {userid[1-9]+}. so basically we just wrap the raw parameter name with the start (and end) dynamic symbols of each router implementing the RouterReversionPolicy. It's an optional functionality but it can be used to create adaptors without even know the router that the user uses (which can be taken by app.Config.Other[iris.RouterNameConfigKey].
Note: we don't need a function like ToWildcardParam because the developer can use the RouterParam with a combination with RouteWildcardPath.
Example: https://github.com/iris-contrib/adaptors/blob/master/oauth/oauth.go
func (*Framework) RouteWildcardPath ¶
RouteWildcardPath returns a path converted to a 'dynamic' path for example, with the httprouter(wildcard symbol: '*'): ("/static", "path") should return /static/*path ("/myfiles/assets", "anything") should return /myfiles/assets/*anything
func (*Framework) Serve ¶
Serve serves incoming connections from the given listener.
Serve blocks until the given listener returns permanent error.
func (*Framework) Set ¶
func (s *Framework) Set(setters ...OptionSetter)
Set sets an option, configuration field to its Config
func (*Framework) URL ¶
URL returns the subdomain + host + Path(...optional named parameters if route is dynamic) returns an empty string if parse is failed. Used for reverse routing, depends on router adaptor.
Examples: https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_3 (gorillamux) https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_4 (httprouter)
type Handler ¶
type Handler interface {
Serve(ctx *Context) // iris-specific
}
Handler the main Iris Handler interface.
type HandlerFunc ¶
type HandlerFunc func(*Context)
HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
func Prioritize ¶
func Prioritize(r RouteInfo) HandlerFunc
Prioritize is a middleware which executes a route against this path when the request's Path has a prefix of the route's STATIC PART is not executing ExecRoute to determinate if it's valid, for performance reasons if this function is not enough for you and you want to test more than one parameterized path then use the: if c := ExecRoute(r); c == nil { /* move to the next, the route is not valid */ }
You can find the Route by iris.Default.Routes().Lookup("theRouteName") you can set a route name as: myRoute := iris.Default.Get("/mypath", handler)("theRouteName") that will set a name to the route and returns its iris.Route instance for further usage.
if the route found then it executes that and don't continue to the next handler if not found then continue to the next handler
func StaticHandler ¶
func StaticHandler(systemPath string, showList bool, enableGzip bool, exceptRoutes ...RouteInfo) HandlerFunc
StaticHandler returns a new Handler which is ready to serve all kind of static files.
Developers can wrap this handler using the `iris.StripPrefix` for a fixed static path when the result handler is being, finally, registered to a route.
Usage: app := iris.New() ... fileserver := iris.StaticHandler("./static_files", false, false) h := iris.StripPrefix("/static", fileserver) /* http://mydomain.com/static/css/style.css */ app.Get("/static", h) ...
func StripPrefix ¶
func StripPrefix(prefix string, h HandlerFunc) HandlerFunc
StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.
Usage: fileserver := iris.StaticHandler("./static_files", false, false) h := iris.StripPrefix("/static", fileserver) app.Get("/static", h)
func ToHandler ¶
func ToHandler(handler interface{}) HandlerFunc
ToHandler converts different style of handlers that you used to use (usually with third-party net/http middleware) to an iris.HandlerFunc.
Supported types: - .ToHandler(h http.Handler) - .ToHandler(func(w http.ResponseWriter, r *http.Request)) - .ToHandler(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
func (HandlerFunc) Serve ¶
func (h HandlerFunc) Serve(ctx *Context)
Serve implements the Handler, is like ServeHTTP but for Iris
type LogMode ¶
type LogMode uint8
LogMode is the type for the LoggerPolicy write mode. Two modes available: - ProdMode (production level mode) - DevMode (development level mode)
The ProdMode should output only fatal errors The DevMode ouputs the rest of the errors
Iris logs ONLY errors at both cases. By-default ONLY ProdMode level messages are printed to the os.Stdout.
const ( // ProdMode the production level logger write mode, // responsible to fatal errors, errors that happen which // your app can't continue running. ProdMode LogMode = iota // DevMode is the development level logger write mode, // responsible to the rest of the errors, for example // if you set a app.Favicon("myfav.ico"..) and that fav doesn't exists // in your system, then it printed by DevMode and app.Favicon simple doesn't works. // But the rest of the app can continue running, so it's not 'Fatal error' DevMode )
type LoggerPolicy ¶
LoggerPolicy is a simple interface which is used to log mostly system panics exception for general debugging messages is when the `Framework.Config.IsDevelopment = true`. It should prints to the logger. Arguments should be handled in the manner of fmt.Printf.
func DevLogger ¶
func DevLogger() LoggerPolicy
DevLogger returns a new Logger which prints both ProdMode and DevMode messages to the default global logger printer.
Usage: app := iris.New()
app.Adapt(iris.DevLogger())
Users can always ignore that and adapt a custom LoggerPolicy, which will use your custom printer instead.
func (LoggerPolicy) Adapt ¶
func (l LoggerPolicy) Adapt(frame *Policies)
Adapt adapts a Logger to the main policies.
func (LoggerPolicy) ToLogger ¶
func (l LoggerPolicy) ToLogger(flag int) *log.Logger
ToLogger returns a new *log.Logger which prints to the the LoggerPolicy function this is used when your packages needs explicit an *log.Logger.
Note: Each time you call it, it returns a new *log.Logger.
func (LoggerPolicy) Write ¶
func (l LoggerPolicy) Write(p []byte) (n int, err error)
The write method exists to LoggerPolicy to be able to passed as a valid an io.Writer when you need it.
Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p). Write must not modify the slice data, even temporarily.
Implementations must not retain p.
Note: this Write writes as the DevMode.
type MethodChangedListener ¶
MethodChangedListener listener signature fired when route method changes
type Middleware ¶
type Middleware []Handler
Middleware is just a slice of Handler []func(c *Context)
type OptionSet ¶
type OptionSet func(c *Configuration)
OptionSet implements the OptionSetter
func (OptionSet) Set ¶
func (o OptionSet) Set(c *Configuration)
Set is the func which makes the OptionSet an OptionSetter, this is used mostly
type OptionSetter ¶
type OptionSetter interface { // Set receives a pointer to the global Configuration type and does the job of filling it Set(c *Configuration) }
OptionSetter sets a configuration field to the main configuration used to help developers to write less and configure only what they really want and nothing else.
Usage: iris.New(iris.Configuration{Charset: "UTF-8", Gzip:true}) now can be done also by using iris.Option$FIELD: iris.New(iris.OptionCharset("UTF-8"), iris.OptionGzip(true))
Benefits:
- Developers have no worries what option to pass, they can just type iris.Option and all options should be visible to their editor's autocomplete-popup window
- Can be passed with any order
- Can override previous configuration
type Policies ¶
type Policies struct { LoggerPolicy EventPolicy RouterReversionPolicy RouterBuilderPolicy RouterWrapperPolicy RenderPolicy TemplateFuncsPolicy SessionsPolicy }
Policies is the main policies list, the rest of the objects that implement the Policy are adapted to the object which contains a field of type *Policies.
Policies can have nested policies behaviors too. See iris.go field: 'policies' and function 'Adapt' for more.
type Policy ¶
type Policy interface { // Adapt receives the main *Policies which the Policy should be attached on. Adapt(frame *Policies) }
Policy is an interface which should be implemented by all modules that can adapt a policy to the Framework. With a Policy you can change the behavior of almost each of the existing Iris' features.
type RenderOptions ¶
type RenderOptions map[string]interface{}
RenderOptions is a helper type for the optional runtime options can be passed by user when Render called. I.e the "layout" or "gzip" option same as iris.Map but more specific name
type RenderPolicy ¶
type RenderPolicy func(out io.Writer, name string, bind interface{}, options ...map[string]interface{}) (bool, error)
RenderPolicy is the type which you can adapt custom renderers based on the 'name', simple as that. Note that the whole template view system and content negotiation works by setting this function via other adaptors.
The functions are wrapped, like any other policy func, the only difference is that here the developer has a priority over the defaults:
- the last registered is trying to be executed first
- the first registered is executing last.
So a custom adaptor that the community can create and share with each other can override the existing one with just a simple registration.
func (RenderPolicy) Adapt ¶
func (r RenderPolicy) Adapt(frame *Policies)
Adapt adaps a RenderPolicy object to the main *Policies.
type ResponseRecorder ¶
type ResponseRecorder struct {
// contains filtered or unexported fields
}
A ResponseRecorder is used mostly by context's transactions in order to record and change if needed the body, status code and headers.
You are NOT limited to use that too: just call context.ResponseWriter.Recorder()/Record() and response writer will act like context.ResponseWriter.(*iris.ResponseRecorder)
func (*ResponseRecorder) Body ¶
func (w *ResponseRecorder) Body() []byte
Body returns the body tracked from the writer so far do not use this for edit.
func (ResponseRecorder) CloseNotify ¶
func (w ResponseRecorder) CloseNotify() <-chan bool
CloseNotify returns a channel that receives at most a single value (true) when the client connection has gone away.
CloseNotify may wait to notify until Request.Body has been fully read.
After the Handler has returned, there is no guarantee that the channel receives a value.
If the protocol is HTTP/1.1 and CloseNotify is called while processing an idempotent request (such a GET) while HTTP/1.1 pipelining is in use, the arrival of a subsequent pipelined request may cause a value to be sent on the returned channel. In practice HTTP/1.1 pipelining is not enabled in browsers and not seen often in the wild. If this is a problem, use HTTP/2 or only use CloseNotify on methods such as POST.
func (ResponseRecorder) ContentType ¶
func (w ResponseRecorder) ContentType() string
ContentType returns the content type, if not setted returns empty string
func (*ResponseRecorder) Flush ¶
func (w *ResponseRecorder) Flush()
Flush sends any buffered data to the client.
func (*ResponseRecorder) Header ¶
func (w *ResponseRecorder) Header() http.Header
Header returns the header map that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example). To suppress implicit response headers, set their value to nil.
func (ResponseRecorder) Hijack ¶
func (w ResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack lets the caller take over the connection. After a call to Hijack(), the HTTP server library will not do anything else with the connection.
It becomes the caller's responsibility to manage and close the connection.
The returned net.Conn may have read or write deadlines already set, depending on the configuration of the Server. It is the caller's responsibility to set or clear those deadlines as needed.
func (*ResponseRecorder) Push ¶
func (w *ResponseRecorder) Push(target string, opts *http.PushOptions) error
Push initiates an HTTP/2 server push. This constructs a synthetic request using the given target and options, serializes that request into a PUSH_PROMISE frame, then dispatches that request using the server's request handler. If opts is nil, default options are used.
The target must either be an absolute path (like "/path") or an absolute URL that contains a valid host and the same scheme as the parent request. If the target is a path, it will inherit the scheme and host of the parent request.
The HTTP/2 spec disallows recursive pushes and cross-authority pushes. Push may or may not detect these invalid pushes; however, invalid pushes will be detected and canceled by conforming clients.
Handlers that wish to push URL X should call Push before sending any data that may trigger a request for URL X. This avoids a race where the client issues requests for X before receiving the PUSH_PROMISE for X.
Push returns ErrPushNotSupported if the client has disabled push or if push is not supported on the underlying connection.
func (*ResponseRecorder) ReseAllHeaders ¶
func (w *ResponseRecorder) ReseAllHeaders()
ReseAllHeaders clears all headers, both temp and underline's response writer
func (*ResponseRecorder) Reset ¶
func (w *ResponseRecorder) Reset()
Reset resets the response body, headers and the status code header
func (*ResponseRecorder) ResetBody ¶
func (w *ResponseRecorder) ResetBody()
ResetBody resets the response body
func (*ResponseRecorder) ResetHeaders ¶
func (w *ResponseRecorder) ResetHeaders()
ResetHeaders clears the temp headers
func (ResponseRecorder) SetBeforeFlush ¶
func (w ResponseRecorder) SetBeforeFlush(cb func())
SetBeforeFlush registers the unique callback which called exactly before the response is flushed to the client
func (*ResponseRecorder) SetBody ¶
func (w *ResponseRecorder) SetBody(b []byte)
SetBody overrides the body and sets it to a slice of bytes value
func (*ResponseRecorder) SetBodyString ¶
func (w *ResponseRecorder) SetBodyString(s string)
SetBodyString overrides the body and sets it to a string value
func (ResponseRecorder) SetContentType ¶
func (w ResponseRecorder) SetContentType(cType string)
SetContentType sets the content type header
func (ResponseRecorder) StatusCode ¶
func (w ResponseRecorder) StatusCode() int
StatusCode returns the status code header value
func (*ResponseRecorder) Write ¶
func (w *ResponseRecorder) Write(contents []byte) (int, error)
Adds the contents to the body reply, it writes the contents temporarily to a value in order to be flushed at the end of the request, this method give us the opportunity to reset the body if needed.
If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.
Depending on the HTTP protocol version and the client, calling Write or WriteHeader may prevent future reads on the Request.Body. For HTTP/1.x requests, handlers should read any needed request body data before writing the response. Once the headers have been flushed (due to either an explicit Flusher.Flush call or writing enough data to trigger a flush), the request body may be unavailable. For HTTP/2 requests, the Go HTTP server permits handlers to continue to read the request body while concurrently writing the response. However, such behavior may not be supported by all HTTP/2 clients. Handlers should read before writing if possible to maximize compatibility.
func (ResponseRecorder) WriteHeader ¶
func (w ResponseRecorder) WriteHeader(statusCode int)
WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.
func (*ResponseRecorder) WriteString ¶
func (w *ResponseRecorder) WriteString(s string) (n int, err error)
WriteString writes a simple string to the response.
Returns the number of bytes written and any write error encountered
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter http.Flusher http.Hijacker http.CloseNotifier // breaks go 1.7 as well as the *PushOptions. // New users should upgrade to 1.8 if they want to use Iris. http.Pusher Writef(format string, a ...interface{}) (n int, err error) WriteString(s string) (n int, err error) SetContentType(cType string) ContentType() string StatusCode() int SetBeforeFlush(cb func()) // contains filtered or unexported methods }
ResponseWriter interface is used by the context to serve an HTTP handler to construct an HTTP response.
A ResponseWriter may not be used after the Handler.ServeHTTP method has returned.
type RouteInfo ¶
type RouteInfo interface { // ChangeName & AllowOPTIONS are the only one route property // which can be change without any bad side-affects // so it's the only setter here. // // It's used on iris.Default.Handle() ChangeName(name string) RouteInfo // Name returns the name of the route Name() string // Method returns the http method Method() string // AllowOPTIONS called when this route is targeting OPTIONS methods too // it's an alternative way of registring the same route with '.OPTIONS("/routepath", routeMiddleware)' AllowOPTIONS() RouteInfo // HasCors returns true if the route is targeting OPTIONS methods too // or it has a middleware which conflicts with "httpmethod", // otherwise false HasCors() bool // Subdomain returns the subdomain,if any Subdomain() string // Path returns the path Path() string // Middleware returns the slice of Handler([]Handler) registered to this route Middleware() Middleware // IsOnline returns true if the route is marked as "online" (state) IsOnline() bool }
RouteInfo is just the (other idea was : RouteInfo but we needed the Change/SetName visible so...) information of the registered routes.
type RouteRepository ¶
type RouteRepository interface { RoutesInfo ChangeName(routeInfo RouteInfo, newName string) ChangeMethod(routeInfo RouteInfo, newMethod string) ChangePath(routeInfo RouteInfo, newPath string) ChangeMiddleware(routeInfo RouteInfo, newMiddleware Middleware) }
RouteRepository contains the interface which is used on custom routers contains methods and helpers to find a route by its name, and change its method, path, middleware.
This is not visible outside except the RouterBuilderPolicy
type Router ¶
type Router struct { // the global errors registry Errors *ErrorHandlers Context ContextPool // contains filtered or unexported fields }
Router the visible api for RESTFUL
func (*Router) Any ¶
func (router *Router) Any(registeredPath string, handlersFn ...HandlerFunc)
Any registers a route for ALL of the http methods (Get,Post,Put,Head,Patch,Options,Connect,Delete)
func (*Router) Connect ¶
func (router *Router) Connect(path string, handlersFn ...HandlerFunc) RouteInfo
Connect registers a route for the Connect http method
func (*Router) Delete ¶
func (router *Router) Delete(path string, handlersFn ...HandlerFunc) RouteInfo
Delete registers a route for the Delete http method
func (*Router) Done ¶
Done registers Handler 'middleware' the only difference from .Use is that it should be used BEFORE any party route registered or AFTER ALL party's routes have been registered.
returns itself
func (*Router) DoneFunc ¶
func (router *Router) DoneFunc(handlersFn ...HandlerFunc) *Router
DoneFunc registers HandlerFunc 'middleware' the only difference from .Use is that it should be used BEFORE any party route registered or AFTER ALL party's routes have been registered.
returns itself
func (*Router) EmitError ¶
EmitError fires a custom http error handler to the client
if no custom error defined with this statuscode, then iris creates one, and once at runtime
func (*Router) Favicon ¶
Favicon serves static favicon accepts 2 parameters, second is optional favPath (string), declare the system directory path of the __.ico requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first, you can declare your own path if you have more than one favicon (desktop, mobile and so on)
this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico (nothing special that you can't handle by yourself) Note that you have to call it on every favicon you have to serve automatically (desktop, mobile and so on)
panics on error
func (*Router) Get ¶
func (router *Router) Get(path string, handlersFn ...HandlerFunc) RouteInfo
Get registers a route for the Get http method
func (*Router) Handle ¶
Handle registers a route to the server's router if empty method is passed then registers handler(s) for all methods, same as .Any, but returns nil as result
func (*Router) HandleFunc ¶
func (router *Router) HandleFunc(method string, registeredPath string, handlersFn ...HandlerFunc) RouteInfo
HandleFunc registers and returns a route with a method string, path string and a handler registeredPath is the relative url path
func (*Router) Head ¶
func (router *Router) Head(path string, handlersFn ...HandlerFunc) RouteInfo
Head registers a route for the Head http method
func (*Router) Layout ¶
Layout oerrides the parent template layout with a more specific layout for this Party returns this Party, to continue as normal example: my := iris.Default.Party("/my").Layout("layouts/mylayout.html")
{ my.Get("/", func(ctx *iris.Context) { ctx.MustRender("page1.html", nil) }) }
func (*Router) None ¶
func (router *Router) None(path string, handlersFn ...HandlerFunc) RouteInfo
None registers an "offline" route see context.ExecRoute(routeName), iris.Default.None(...) and iris.Default.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585
Example: https://github.com/iris-contrib/examples/tree/master/route_state
func (*Router) OnError ¶
func (router *Router) OnError(statusCode int, handlerFn HandlerFunc, rgexp ...string)
OnError registers a custom http error handler. Accepts the status code which the 'handlerFn' should be fired, third parameter is OPTIONAL, if setted then the 'handlerFn' will be executed only when this regex expression will be validated and matched to the ctx.Request.RequestURI, keep note that it will compare the whole request path but the error handler owns to this Party, this gives developers power tooling.
Each party's static path prefix can have a set of its own error handlers, this works by wrapping the error handlers, so if a party doesn't needs a custom error handler, then it will execute the root's one (if setted, otherwise the framework creates one at runtime).
func (*Router) Options ¶
func (router *Router) Options(path string, handlersFn ...HandlerFunc) RouteInfo
Options registers a route for the Options http method
func (*Router) Party ¶
func (router *Router) Party(relativePath string, handlersFn ...HandlerFunc) *Router
Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. Party can also be named as 'Join' or 'Node' or 'Group' , Party chosen because it has more fun
func (*Router) Patch ¶
func (router *Router) Patch(path string, handlersFn ...HandlerFunc) RouteInfo
Patch registers a route for the Patch http method
func (*Router) Post ¶
func (router *Router) Post(path string, handlersFn ...HandlerFunc) RouteInfo
Post registers a route for the Post http method
func (*Router) Put ¶
func (router *Router) Put(path string, handlersFn ...HandlerFunc) RouteInfo
Put registers a route for the Put http method
func (*Router) Routes ¶
func (router *Router) Routes() RoutesInfo
Routes returns the routes information, some of them can be changed at runtime some others not the result of this RoutesInfo is safe to use at RUNTIME.
func (*Router) StaticContent ¶
StaticContent serves bytes, memory cached, on the reqPath a good example of this is how the websocket server uses that to auto-register the /iris-ws.js
func (*Router) StaticEmbedded ¶
func (router *Router) StaticEmbedded(requestPath string, vdir string, assetFn func(name string) ([]byte, error), namesFn func() []string) RouteInfo
StaticEmbedded used when files are distributed inside the app executable, using go-bindata mostly First parameter is the request path, the path which the files in the vdir will be served to, for example "/static" Second parameter is the (virtual) directory path, for example "./assets" Third parameter is the Asset function Forth parameter is the AssetNames function
For more take a look at the example: https://github.com/iris-contrib/examples/tree/master/static_files_embedded
func (*Router) StaticHandler ¶
func (router *Router) StaticHandler(reqPath string, systemPath string, showList bool, enableGzip bool, exceptRoutes ...RouteInfo) HandlerFunc
StaticHandler returns a new Handler which is ready to serve all kind of static files.
Note: The only difference from package-level `StaticHandler` is that this `StaticHandler“ receives a request path which is appended to the party's relative path and stripped here, so `iris.StripPath` is useless and should not being used here.
Usage: app := iris.New() ... mySubdomainFsServer := app.Party("mysubdomain.") h := mySubdomainFsServer.StaticHandler("/static", "./static_files", false, false) /* http://mysubdomain.mydomain.com/static/css/style.css */ mySubdomainFsServer.Get("/static", h) ...
func (*Router) StaticServe ¶
StaticServe serves a directory as web resource it's the simpliest form of the Static* functions Almost same usage as StaticWeb accepts only one required parameter which is the systemPath ( the same path will be used to register the GET&HEAD routes) if second parameter is empty, otherwise the requestPath is the second parameter it uses gzip compression (compression on each request, no file cache)
func (*Router) StaticWeb ¶
func (router *Router) StaticWeb(reqPath string, systemPath string, exceptRoutes ...RouteInfo) RouteInfo
StaticWeb returns a handler that serves HTTP requests with the contents of the file system rooted at directory.
first parameter: the route path second parameter: the system directory third OPTIONAL parameter: the exception routes
(= give priority to these routes instead of the static handler)
for more options look router.StaticHandler.
router.StaticWeb("/static", "./static")
As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".
StaticWeb calls the StaticHandler(reqPath, systemPath, listingDirectories: false, gzip: false ).
func (*Router) Trace ¶
func (router *Router) Trace(path string, handlersFn ...HandlerFunc) RouteInfo
Trace registers a route for the Trace http method
func (*Router) UseFunc ¶
func (router *Router) UseFunc(handlersFn ...HandlerFunc) *Router
UseFunc registers HandlerFunc middleware returns itself
func (*Router) UseGlobal ¶
UseGlobal registers Handler middleware to the beginning, prepends them instead of append
Use it when you want to add a global middleware to all parties, to all routes in all subdomains It should be called right before Listen functions
func (*Router) UseGlobalFunc ¶
func (router *Router) UseGlobalFunc(handlersFn ...HandlerFunc)
UseGlobalFunc registers HandlerFunc middleware to the beginning, prepends them instead of append
Use it when you want to add a global middleware to all parties, to all routes in all subdomains It should be called right before Listen functions
type RouterBuilderPolicy ¶
type RouterBuilderPolicy func(repo RouteRepository, cPool ContextPool) http.Handler
RouterBuilderPolicy is the most useful Policy for custom routers. A custom router should adapt this policy which is a func accepting a route repository (contains all necessary routes information) and a context pool which should be used inside router's handlers.
func (RouterBuilderPolicy) Adapt ¶
func (r RouterBuilderPolicy) Adapt(frame *Policies)
Adapt adaps a RouterBuilderPolicy object to the main *Policies.
type RouterReversionPolicy ¶
type RouterReversionPolicy struct { // StaticPath should return the static part of the route path // for example, with the httprouter(: and *): // /api/user/:userid should return /api/user // /api/user/:userid/messages/:messageid should return /api/user // /dynamicpath/*path should return /dynamicpath // /my/path should return /my/path StaticPath func(path string) string // WildcardPath should return a path converted to a 'dynamic' path // for example, with the httprouter(wildcard symbol: '*'): // ("/static", "path") should return /static/*path // ("/myfiles/assets", "anything") should return /myfiles/assets/*anything WildcardPath func(path string, paramName string) string // Param should return a named parameter as each router defines named path parameters. // For example, with the httprouter(: as named param symbol): // userid should return :userid. // with gorillamux, userid should return {userid} // or userid[1-9]+ should return {userid[1-9]+}. // so basically we just wrap the raw parameter name // with the start (and end) dynamic symbols of each router implementing the RouterReversionPolicy. // It's an optional functionality but it can be used to create adaptors without even know the router // that the user uses (which can be taken by app.Config.Other[iris.RouterNameConfigKey]. // // Note: we don't need a function like WildcardParam because the developer // can use the Param with a combination with WildcardPath. Param func(paramName string) string // URLPath used for reverse routing on templates with {{ url }} and {{ path }} funcs. // Receives the route name and arguments and returns its http path URLPath func(r RouteInfo, args ...string) string }
RouterReversionPolicy is used for the reverse routing feature on which custom routers should create and adapt to the Policies.
func (RouterReversionPolicy) Adapt ¶
func (r RouterReversionPolicy) Adapt(frame *Policies)
Adapt adaps a RouterReversionPolicy object to the main *Policies.
type RouterWrapperPolicy ¶
type RouterWrapperPolicy func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
RouterWrapperPolicy is the Policy which enables a wrapper on the top of the builded Router. Usually it's useful for third-party middleware when need to wrap the entire application with a middleware like CORS.
Developers can Adapt more than one RouterWrapper those wrappers' execution comes from last to first. That means that the second wrapper will wrap the first, and so on.
func (RouterWrapperPolicy) Adapt ¶
func (rw RouterWrapperPolicy) Adapt(frame *Policies)
Adapt adaps a RouterWrapperPolicy object to the main *Policies.
type RoutesInfo ¶
type RoutesInfo interface { Lookup(routeName string) RouteInfo Visit(visitor func(RouteInfo)) OnMethodChanged(methodChangedListener MethodChangedListener) Online(routeInfo RouteInfo, HTTPMethod string) bool Offline(routeInfo RouteInfo) bool }
RoutesInfo is the interface which contains the valid actions permitted at RUNTIME
type Session ¶
type Session interface { ID() string Get(string) interface{} HasFlash() bool GetFlash(string) interface{} GetString(key string) string GetFlashString(string) string GetInt(key string) (int, error) GetInt64(key string) (int64, error) GetFloat32(key string) (float32, error) GetFloat64(key string) (float64, error) GetBoolean(key string) (bool, error) GetAll() map[string]interface{} GetFlashes() map[string]interface{} VisitAll(cb func(k string, v interface{})) Set(string, interface{}) SetFlash(string, interface{}) Delete(string) DeleteFlash(string) Clear() ClearFlashes() }
Session should expose the SessionsPolicy's end-user API. This will be returned at the sess := context.Session().
type SessionsPolicy ¶
type SessionsPolicy struct { // Start should starts the session for the particular net/http request Start func(http.ResponseWriter, *http.Request) Session // Destroy should kills the net/http session and remove the associated cookie // Keep note that: Destroy should not called at the end of any handler, it's an independent func. // Start should set // the values at realtime and if manager doesn't supports these // then the user manually have to call its 'done' func inside the handler. Destroy func(http.ResponseWriter, *http.Request) }
SessionsPolicy is the policy for a session manager.
A SessionsPolicy should be responsible to Start a sesion based on raw http.ResponseWriter and http.Request, which should return a compatible iris.Session interface, type. If the external session manager doesn't qualifies, then the user should code the rest of the functions with empty implementation.
A SessionsPolicy should be responsible to Destroy a session based on the http.ResponseWriter and http.Request, this function should works individually.
No iris.Context required from users. In order to be able to adapt any external session manager.
The SessionsPolicy should be adapted once.
func (SessionsPolicy) Adapt ¶
func (s SessionsPolicy) Adapt(frame *Policies)
Adapt adaps a SessionsPolicy object to the main *Policies.
Remember: Each policy is an adaptor. An adaptor should contains one or more policies too.
type StaticHandlerBuilder ¶
type StaticHandlerBuilder interface { Gzip(enable bool) StaticHandlerBuilder Listing(listDirectoriesOnOff bool) StaticHandlerBuilder Except(r ...RouteInfo) StaticHandlerBuilder Build() HandlerFunc }
StaticHandlerBuilder is the web file system's Handler builder use that or the iris.StaticHandler/StaticWeb methods
func NewStaticHandlerBuilder ¶
func NewStaticHandlerBuilder(dir string) StaticHandlerBuilder
NewStaticHandlerBuilder returns a new Handler which serves static files supports gzip, no listing and much more Note that, this static builder returns a Handler it doesn't cares about the rest of your iris configuration.
Use the iris.StaticHandler/StaticWeb in order to serve static files on more automatic way this builder is used by people who have more complicated application structure and want a fluent api to work on.
type TCPKeepAliveListener ¶
type TCPKeepAliveListener struct {
*net.TCPListener
}
TCPKeepAliveListener sets TCP keep-alive timeouts on accepted connections. Dead TCP connections (e.g. closing laptop mid-download) eventually go away It is not used by default if you want to pass a keep alive listener then just pass the child listener, example: listener := iris.TCPKeepAliveListener{iris.TCP4(":8080").(*net.TCPListener)}
type TemplateFuncsPolicy ¶
type TemplateFuncsPolicy map[string]interface{} // interface can be: func(arguments ...string) string {}
TemplateFuncsPolicy sets or overrides template func map. Defaults are the iris.URL and iris.Path, all the template engines supports the following: {{ url "mynamedroute" "pathParameter_ifneeded"} } {{ urlpath "mynamedroute" "pathParameter_ifneeded" }} {{ render "header.html" }} {{ render_r "header.html" }} // partial relative path to current page {{ yield }} {{ current }}
Developers can already set the template's func map from the view adaptors, example: view.HTML(...).Funcs(...)), this type exists in order to be possible from third-party developers to create packages that bind template functions to the Iris without the need of knowing what template engine is used by the user or what order of declaration the user should follow.
func (TemplateFuncsPolicy) Adapt ¶
func (t TemplateFuncsPolicy) Adapt(frame *Policies)
Adapt adaps a TemplateFuncsPolicy object to the main *Policies.
type Transaction ¶
type Transaction struct { Context *Context // contains filtered or unexported fields }
Transaction gives the users the opportunity to code their route handlers cleaner and safier it receives a scope which is decided when to send an error to the user, recover from panics stop the execution of the next transactions and so on...
it's default scope is the TransientTransactionScope which is silently skips the current transaction's response if transaction.Complete accepts a non-empty error.
Create and set custom transactions scopes with transaction.SetScope.
For more information please view the tests
func (*Transaction) Complete ¶
func (t *Transaction) Complete(err error)
Complete completes the transaction rollback and send an error when the error is not empty. The next steps depends on its Scope.
The error can be a type of NewTransactionErrResult()
func (*Transaction) SetScope ¶
func (t *Transaction) SetScope(scope TransactionScope)
SetScope sets the current transaction's scope iris.RequestTransactionScope || iris.TransientTransactionScope (default)
type TransactionErrResult ¶
type TransactionErrResult struct { StatusCode int // if reason is empty then the already relative registered (custom or not) // error will be executed if the scope allows that. Reason string ContentType string }
TransactionErrResult could be named also something like 'MaybeError', it is useful to send it on transaction.Complete in order to execute a custom error mesasge to the user.
in simple words it's just a 'traveler message' between the transaction and its scope. it is totally optional
func NewTransactionErrResult ¶
func NewTransactionErrResult() TransactionErrResult
NewTransactionErrResult returns a new transaction result with the given error message, it can be empty too, but if not then the transaction's scope is decided what to do with that
func (TransactionErrResult) Error ¶
func (err TransactionErrResult) Error() string
Error returns the reason given by the user or an empty string
func (TransactionErrResult) IsFailure ¶
func (err TransactionErrResult) IsFailure() bool
IsFailure returns true if this is an actual error
type TransactionScope ¶
type TransactionScope interface { // EndTransaction returns if can continue to the next transactions or not (false) // called after Complete, empty or not empty error EndTransaction(maybeErr TransactionErrResult, ctx *Context) bool }
TransactionScope is the manager of the transaction's response, can be resseted and skipped from its parent context or execute an error or skip other transactions
type TransactionScopeFunc ¶
type TransactionScopeFunc func(maybeErr TransactionErrResult, ctx *Context) bool
TransactionScopeFunc the transaction's scope signature
func (TransactionScopeFunc) EndTransaction ¶
func (tsf TransactionScopeFunc) EndTransaction(maybeErr TransactionErrResult, ctx *Context) bool
EndTransaction ends the transaction with a callback to itself, implements the TransactionScope interface
type Unmarshaler ¶
Unmarshaler is the interface implemented by types that can unmarshal any raw data TIP INFO: Any v object which implements the BodyDecoder can be override the unmarshaler
type UnmarshalerFunc ¶
UnmarshalerFunc a shortcut for the Unmarshaler interface
See 'Unmarshaler' and 'BodyDecoder' for more
func (UnmarshalerFunc) Unmarshal ¶
func (u UnmarshalerFunc) Unmarshal(data []byte, v interface{}) error
Unmarshal parses the X-encoded data and stores the result in the value pointed to by v. Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers as necessary.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_examples
|
|
advanced/subdomains/single
Package main register static subdomains, simple as parties, check ./hosts if you use windows
|
Package main register static subdomains, simple as parties, check ./hosts if you use windows |
advanced/subdomains/wildcard
Package main an example on how to catch dynamic subdomains - wildcard.
|
Package main an example on how to catch dynamic subdomains - wildcard. |
advanced/url-shortener
Package main shows how you can create a simple URL SHortener using only Iris and BoltDB.
|
Package main shows how you can create a simple URL SHortener using only Iris and BoltDB. |
beginner/listen-letsencrypt
Package main provide one-line integration with letsencrypt.org
|
Package main provide one-line integration with letsencrypt.org |
beginner/read-form
package main contains an example on how to use the ReadForm, but with the same way you can do the ReadJSON & ReadJSON
|
package main contains an example on how to use the ReadForm, but with the same way you can do the ReadJSON & ReadJSON |
intermediate/view/context-view-data
this example will show you how you can set per-request data for a template outside of the main handler which calls the .Render, via middleware.
|
this example will show you how you can set per-request data for a template outside of the main handler which calls the .Render, via middleware. |
intermediate/view/embedding-templates-into-app
NOTE: execute your own look main.go
|
NOTE: execute your own look main.go |
intermediate/view/template_html_3
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' HTML Template Engine, same for other template engines. |
intermediate/view/template_html_4
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' HTML Template Engine, same for other template engines. |
adaptors
|
|
sessions
Package sessions as originally written by me at https://github.com/kataras/go-sessions Based on kataras/go-sessions v1.0.1.
|
Package sessions as originally written by me at https://github.com/kataras/go-sessions Based on kataras/go-sessions v1.0.1. |
typescript
Package typescript provides a typescript compiler with hot-reloader and optionally a cloud-based editor, called 'alm-tools'.
|
Package typescript provides a typescript compiler with hot-reloader and optionally a cloud-based editor, called 'alm-tools'. |
view
Package view is the adaptor of the 5 template engines as written by me at https://github.com/kataras/go-template
|
Package view is the adaptor of the 5 template engines as written by me at https://github.com/kataras/go-template |
websocket
Package websocket provides an easy way to setup server and client side rich websocket experience for Iris As originally written by me at https://github.com/kataras/go-websocket based on v0.1.1
|
Package websocket provides an easy way to setup server and client side rich websocket experience for Iris As originally written by me at https://github.com/kataras/go-websocket based on v0.1.1 |
middleware
|
|
pprof
Package pprof usage: app.Get(iris.RouteWildcardPath("/debug/pprof", "action"), pprof.New()) for specific router adaptors follow these optional route syntax: 'adaptors/httprouter': app := iris.New() app.Adapt(httprouter.New()) app.Get("/debug/pprof/*action", pprof.New()) 'adaptors/gorillamux': app := iris.New() app.Adapt(gorillamux.New()) app.Get("/debug/pprof/{action:.*}", pprof.New())
|
Package pprof usage: app.Get(iris.RouteWildcardPath("/debug/pprof", "action"), pprof.New()) for specific router adaptors follow these optional route syntax: 'adaptors/httprouter': app := iris.New() app.Adapt(httprouter.New()) app.Get("/debug/pprof/*action", pprof.New()) 'adaptors/gorillamux': app := iris.New() app.Adapt(gorillamux.New()) app.Get("/debug/pprof/{action:.*}", pprof.New()) |