mirror of
https://github.com/kataras/iris.git
synced 2026-08-07 04:59:01 +00:00
Publish the new version ✈️ | Look description please!
# FAQ ### Looking for free support? http://support.iris-go.com https://kataras.rocket.chat/channel/iris ### Looking for previous versions? https://github.com/kataras/iris#version ### Should I upgrade my Iris? Developers are not forced to upgrade if they don't really need it. Upgrade whenever you feel ready. > Iris uses the [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo) feature, so you get truly reproducible builds, as this method guards against upstream renames and deletes. **How to upgrade**: Open your command-line and execute this command: `go get -u github.com/kataras/iris`. For further installation support, please click [here](http://support.iris-go.com/d/16-how-to-install-iris-web-framework). ### About our new home page http://iris-go.com Thanks to [Santosh Anand](https://github.com/santoshanand) the http://iris-go.com has been upgraded and it's really awesome! [Santosh](https://github.com/santoshanand) is a freelancer, he has a great knowledge of nodejs and express js, Android, iOS, React Native, Vue.js etc, if you need a developer to find or create a solution for your problem or task, please contact with him. The amount of the next two or three donations you'll send they will be immediately transferred to his own account balance, so be generous please! Read more at https://github.com/kataras/iris/blob/master/HISTORY.md Former-commit-id: eec2d71bbe011d6b48d2526eb25919e36e5ad94e
This commit is contained in:
@@ -1,57 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/basicauth"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // adapt a simple internal logger to print any errors
|
||||
app.Adapt(httprouter.New()) // adapt a router, you can use gorillamux too
|
||||
|
||||
authConfig := basicauth.Config{
|
||||
Users: map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"},
|
||||
Realm: "Authorization Required", // defaults to "Authorization Required"
|
||||
ContextKey: "mycustomkey", // defaults to "user"
|
||||
Expires: time.Duration(30) * time.Minute,
|
||||
}
|
||||
|
||||
authentication := basicauth.New(authConfig)
|
||||
app.Get("/", func(ctx *iris.Context) { ctx.Redirect("/admin") })
|
||||
// to global app.Use(authentication) (or app.UseGlobal before the .Listen)
|
||||
// to routes
|
||||
/*
|
||||
app.Get("/mysecret", authentication, func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s ", username)
|
||||
})
|
||||
*/
|
||||
|
||||
// to party
|
||||
|
||||
needAuth := app.Party("/admin", authentication)
|
||||
{
|
||||
//http://localhost:8080/admin
|
||||
needAuth.Get("/", func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
// http://localhost:8080/admin/profile
|
||||
needAuth.Get("/profile", func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
// http://localhost:8080/admin/settings
|
||||
needAuth.Get("/settings", func(ctx *iris.Context) {
|
||||
username := authConfig.User(ctx) // shortcut for ctx.GetString("mycustomkey")
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
}
|
||||
|
||||
// open http://localhost:8080/admin
|
||||
app.Listen(":8080")
|
||||
}
|
||||
@@ -3,15 +3,16 @@ package main
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/cache"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
var testMarkdownContents = `## Hello Markdown
|
||||
var markdownContents = []byte(`## Hello Markdown
|
||||
|
||||
This is a sample of Markdown contents
|
||||
|
||||
|
||||
|
||||
|
||||
Features
|
||||
--------
|
||||
@@ -39,7 +40,7 @@ All features of Sundown are supported, including:
|
||||
* **Fast processing**. It is fast enough to render on-demand in
|
||||
most web applications without having to cache the output.
|
||||
|
||||
* **Thread safety**. You can run multiple parsers in different
|
||||
* **Routine safety**. You can run multiple parsers in different
|
||||
goroutines without ill effect. There is no dependence on global
|
||||
shared state.
|
||||
|
||||
@@ -51,32 +52,55 @@ All features of Sundown are supported, including:
|
||||
* **Standards compliant**. Output successfully validates using the
|
||||
W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional.
|
||||
|
||||
[this is a link](https://github.com/kataras/iris) `
|
||||
[this is a link](https://github.com/kataras/iris) `)
|
||||
|
||||
// Cache should not be used on handlers that contain dynamic data.
|
||||
// Cache is a good and a must-feature on static content, i.e "about page" or for a whole blog site.
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/hi", app.Cache(func(c *iris.Context) {
|
||||
c.WriteString("Hi this is a big content, do not try cache on small content it will not make any significant difference!")
|
||||
}, time.Duration(10)*time.Second))
|
||||
// first argument is the handler which response's we want to apply the cache.
|
||||
// if second argument, expiration, is <=time.Second then the cache tries to set the expiration from the "cache-control" maxage header's value(in seconds)
|
||||
// and if that header is empty or not exist then it sets a default of 5 minutes.
|
||||
writeMarkdownCached := cache.Cache(writeMarkdown, 10*time.Second) // or CacheHandler to get the handler
|
||||
|
||||
bodyHandler := func(ctx *iris.Context) {
|
||||
ctx.Markdown(iris.StatusOK, testMarkdownContents)
|
||||
}
|
||||
app.Get("/", writeMarkdownCached.ServeHTTP)
|
||||
// saves its content on the first request and serves it instead of re-calculating the content.
|
||||
// After 10 seconds it will be cleared and resetted.
|
||||
|
||||
expiration := time.Duration(5 * time.Second)
|
||||
|
||||
app.Get("/", app.Cache(bodyHandler, expiration))
|
||||
|
||||
// if expiration is <=time.Second then the cache tries to set the expiration from the "cache-control" maxage header's value(in seconds)
|
||||
// // if this header doesn't founds then the default is 5 minutes
|
||||
app.Get("/cache_control", app.Cache(func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, "<h1>Hello!</h1>")
|
||||
}, -1))
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func writeMarkdown(ctx context.Context) {
|
||||
// tap multiple times the browser's refresh button and you will
|
||||
// see this println only once every 10 seconds.
|
||||
println("Handler executed. Content refreshed.")
|
||||
|
||||
ctx.Markdown(markdownContents)
|
||||
}
|
||||
|
||||
// Notes:
|
||||
// Cached handler is not changing your pre-defined headers,
|
||||
// so it will not send any additional headers to the client.
|
||||
// The cache happening at the server-side's memory.
|
||||
//
|
||||
// see "DefaultRuleSet" in "cache/client/ruleset.go" to see how you can add separated
|
||||
// rules to each of the cached handlers (`.AddRule`) with the help of "/cache/client/rule"'s definitions.
|
||||
//
|
||||
// The default rules are:
|
||||
/*
|
||||
// #1 A shared cache MUST NOT use a cached response to a request with an
|
||||
// Authorization header field
|
||||
rule.HeaderClaim(ruleset.AuthorizationRule),
|
||||
// #2 "must-revalidate" and/or
|
||||
// "s-maxage" response directives are not allowed to be served stale
|
||||
// (Section 4.2.4) by shared caches. In particular, a response with
|
||||
// either "max-age=0, must-revalidate" or "s-maxage=0" cannot be used to
|
||||
// satisfy a subsequent request without revalidating it on the origin
|
||||
// server.
|
||||
rule.HeaderClaim(ruleset.MustRevalidateRule),
|
||||
rule.HeaderClaim(ruleset.ZeroMaxAgeRule),
|
||||
// #3 custom No-Cache header used inside this library
|
||||
// for BOTH request and response (after get-cache action)
|
||||
rule.Header(ruleset.NoCacheRule, ruleset.NoCacheRule)
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
|
||||
"github.com/kataras/iris/typescript" // optionally
|
||||
"github.com/kataras/iris/typescript/editor"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// adapt a router, order doesn't matters
|
||||
|
||||
// optionally but good to have, I didn't put inside editor or the editor in the typescript compiler adaptors
|
||||
// because you may use tools like gulp and you may use the editor without the typescript compiler adaptor.
|
||||
// but if you need auto-compilation on .ts, we have a solution:
|
||||
ts := typescript.New()
|
||||
ts.Config.Dir = "./www/scripts/"
|
||||
ts.Attach(app) // attach the typescript compiler adaptor
|
||||
|
||||
editorConfig := editor.Config{
|
||||
Hostname: "localhost",
|
||||
Port: 4444,
|
||||
WorkingDir: "./www/scripts/", // "/path/to/the/client/side/directory/",
|
||||
Username: "myusername",
|
||||
Password: "mypassword",
|
||||
}
|
||||
e := editor.New(editorConfig)
|
||||
e.Attach(app) // attach the editor
|
||||
|
||||
app.StaticWeb("/", "./www") // serve the index.html
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Load my script (lawl)</title>
|
||||
</head>
|
||||
<body>
|
||||
<script src="scripts/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
class User{
|
||||
private name: string;
|
||||
|
||||
constructor(fullname:string) {
|
||||
this.name = fullname;
|
||||
}
|
||||
|
||||
Hi(msg: string): string {
|
||||
return msg + " " + this.name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
var user = new User("kataras");
|
||||
var hi = user.Hi("Hello");
|
||||
window.alert(hi);
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"noImplicitAny": false,
|
||||
"removeComments": true,
|
||||
"preserveConstEnums": true,
|
||||
"sourceMap": false,
|
||||
"target": "ES5",
|
||||
"noEmit": false,
|
||||
"watch":true,
|
||||
"noEmitOnError": true,
|
||||
"experimentalDecorators": false,
|
||||
"outDir": "./",
|
||||
"charset": "UTF-8",
|
||||
"noLib": false,
|
||||
"diagnostics": true,
|
||||
"declaration": false
|
||||
},
|
||||
"files": [
|
||||
"./app.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,43 +1,57 @@
|
||||
package main
|
||||
|
||||
// We don't have to reinvert the wheel, so we will use a good cors middleware
|
||||
// as a router wrapper for our entire app.
|
||||
// Follow the steps below:
|
||||
// +------------------------------------------------------------+
|
||||
// | Cors installation |
|
||||
// +------------------------------------------------------------+
|
||||
// go get -u github.com/rs/cors
|
||||
//
|
||||
// +------------------------------------------------------------+
|
||||
// | Cors wrapper usage |
|
||||
// +------------------------------------------------------------+
|
||||
// import "github.com/rs/cors"
|
||||
//
|
||||
// app := iris.New()
|
||||
// corsOptions := cors.Options{/* your options here */}
|
||||
// corsWrapper := cors.New(corsOptions).ServeHTTP
|
||||
// app.Wrap(corsWrapper)
|
||||
//
|
||||
// [your code goes here...]
|
||||
//
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/cors"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/rs/cors"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
crs := cors.New(cors.Options{
|
||||
corsOptions := cors.Options{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowCredentials: true,
|
||||
})
|
||||
}
|
||||
|
||||
app.Adapt(crs) // this line should be added
|
||||
// adaptor supports cors allowed methods, middleware does not.
|
||||
corsWrapper := cors.New(corsOptions).ServeHTTP
|
||||
|
||||
// if you want per-route-only cors
|
||||
// then you should check https://github.com/iris-contrib/middleware/tree/master/cors
|
||||
app.WrapRouter(corsWrapper)
|
||||
|
||||
v1 := app.Party("/api/v1")
|
||||
{
|
||||
v1.Post("/home", func(c *iris.Context) {
|
||||
app.Log(iris.DevMode, "lalala")
|
||||
c.WriteString("Hello from /home")
|
||||
})
|
||||
v1.Get("/g", func(c *iris.Context) {
|
||||
app.Log(iris.DevMode, "lalala")
|
||||
c.WriteString("Hello from /home")
|
||||
})
|
||||
v1.Post("/h", func(c *iris.Context) {
|
||||
app.Log(iris.DevMode, "lalala")
|
||||
c.WriteString("Hello from /home")
|
||||
})
|
||||
v1.Get("/", h)
|
||||
v1.Put("/put", h)
|
||||
v1.Post("/post", h)
|
||||
}
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func h(ctx context.Context) {
|
||||
ctx.Application().Log(ctx.Path())
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package main
|
||||
|
||||
// In this package I'll show you how to override the existing Context's functions and methods.
|
||||
// You can easly navigate to the advanced/custom-context to see how you can add new functions
|
||||
// to your own context (need a custom handler).
|
||||
//
|
||||
// This way is far easier to understand and it's faster when you want to override existing methods:
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
// Create your own custom Context, put any fields you wanna need.
|
||||
type MyContext struct {
|
||||
// Optional Part 1: embed (optional but required if you don't want to override all context's methods)
|
||||
context.Context // it's the internal/Context.go but you don't need to know it.
|
||||
}
|
||||
|
||||
var _ context.Context = &MyContext{} // optionally: validate on compile-time if MyContext implements context.Context.
|
||||
|
||||
// Optional Part 2:
|
||||
// The only one important if you will override the Context with an embedded context.Context inside it.
|
||||
func (ctx *MyContext) Next() {
|
||||
context.Next(ctx)
|
||||
}
|
||||
|
||||
// Override any context's method you want...
|
||||
// [...]
|
||||
|
||||
func (ctx *MyContext) HTML(htmlContents string) (int, error) {
|
||||
ctx.Application().Log("Executing .HTML function from MyContext")
|
||||
|
||||
ctx.ContentType("text/html")
|
||||
return ctx.WriteString(htmlContents)
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// Register a view engine on .html files inside the ./view/** directory.
|
||||
viewEngine := view.HTML("./view", ".html")
|
||||
app.AttachView(viewEngine)
|
||||
|
||||
// Register the session manager.
|
||||
sessionManager := sessions.New(sessions.Config{
|
||||
Cookie: "myappcookieid",
|
||||
})
|
||||
app.AttachSessionManager(sessionManager)
|
||||
|
||||
// The only one Required:
|
||||
// here is how you define how your own context will be created and acquired from the iris' generic context pool.
|
||||
app.ContextPool.Attach(func() context.Context {
|
||||
return &MyContext{
|
||||
// Optional Part 3:
|
||||
Context: context.NewContext(app),
|
||||
}
|
||||
})
|
||||
|
||||
// register your route, as you normally do
|
||||
app.Handle("GET", "/", recordWhichContetsJustForProofOfConcept, func(ctx context.Context) {
|
||||
// use the context's overridden HTML method.
|
||||
ctx.HTML("<h1> Hello from my custom context's HTML! </h1>")
|
||||
})
|
||||
|
||||
// this will be executed by the MyContext.Context
|
||||
// if MyContext is not directly define the View function by itself.
|
||||
app.Handle("GET", "/hi/{firstname:alphabetical}", recordWhichContetsJustForProofOfConcept, func(ctx context.Context) {
|
||||
firstname := ctx.Values().GetString("firstname")
|
||||
|
||||
ctx.ViewData("firstname", firstname)
|
||||
ctx.Gzip(true)
|
||||
|
||||
ctx.View("hi.html")
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
// should always print "($PATH) Handler is executing from 'MyContext'"
|
||||
func recordWhichContetsJustForProofOfConcept(ctx context.Context) {
|
||||
ctx.Application().Log("(%s) Handler is executing from: '%s'", ctx.Path(), reflect.TypeOf(ctx).Elem().Name())
|
||||
ctx.Next()
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<h1> Hi {{.firstname}} </h1>
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
srv := &http.Server{Addr: ":8080" /* Any custom fields here: Handler and ErrorLog are setted to the server automatically */}
|
||||
// http://localhost:8080/
|
||||
// http://localhost:8080/mypath
|
||||
app.Run(iris.Server(srv)) // same as app.Run(iris.Addr(":8080"))
|
||||
|
||||
// More:
|
||||
// see "multi" if you need to use more than one server at the same app.
|
||||
//
|
||||
// for a custom listener use: iris.Listener(net.Listener) or
|
||||
// iris.TLS(cert,key) or iris.AutoTLS(), see "custom-listener" example for those.
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// call .Boot before use the 'app' as an http.Handler on a custom http.Server
|
||||
app.Boot()
|
||||
|
||||
// create our custom fasthttp server and assign the Handler/Router
|
||||
fsrv := &http.Server{Handler: app, Addr: ":8080"}
|
||||
fsrv.ListenAndServe()
|
||||
|
||||
// navigate to http://127.0.0.1:8080/mypath
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// Note: It's not needed if the first action is "go app.Run".
|
||||
if err := app.Build(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// start a secondary server listening on localhost:9090.
|
||||
// use "go" keyword for Listen functions if you need to use more than one server at the same app.
|
||||
//
|
||||
// http://localhost:9090/
|
||||
// http://localhost:9090/mypath
|
||||
srv1 := &http.Server{Addr: ":9090", Handler: app}
|
||||
go srv1.ListenAndServe()
|
||||
println("Start a server listening on http://localhost:9090")
|
||||
|
||||
// start a "second-secondary" server listening on localhost:5050.
|
||||
//
|
||||
// http://localhost:5050/
|
||||
// http://localhost:5050/mypath
|
||||
srv2 := &http.Server{Addr: ":5050", Handler: app}
|
||||
go srv2.ListenAndServe()
|
||||
println("Start a server listening on http://localhost:5050")
|
||||
|
||||
// Note: app.Run is totally optional, we have already built the app with app.Build,
|
||||
// you can just make a new http.Server instead.
|
||||
// http://localhost:8080/
|
||||
// http://localhost:8080/mypath
|
||||
app.Run(iris.Addr(":8080")) // Block here.
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// call .Build before use the 'app' as an http.Handler on a custom http.Server
|
||||
if err := app.Build(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// create our custom server and assign the Handler/Router
|
||||
srv := &http.Server{Handler: app, Addr: ":8080"} // you have to set Handler:app and Addr, see "iris-way" which does this automatically.
|
||||
// http://localhost:8080/
|
||||
// http://localhost:8080/mypath
|
||||
println("Start a server listening on http://localhost:8080")
|
||||
srv.ListenAndServe() // same as app.Run(iris.Addr(":8080"))
|
||||
|
||||
// Notes:
|
||||
// Banne and Tray are not shown at all. Same for the Interrupt Handler, even if app's configuration allows them.
|
||||
//
|
||||
// `.Run` is the only one function that cares about those three.
|
||||
|
||||
// More:
|
||||
// see "multi" if you need to use more than one server at the same app.
|
||||
//
|
||||
// for a custom listener use: iris.Listener(net.Listener) or
|
||||
// iris.TLS(cert,key) or iris.AutoTLS(), see "custom-listener" example for those.
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// create our custom listener
|
||||
ln, err := net.Listen("tcp4", ":8080")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// use of the custom listener
|
||||
app.Serve(ln)
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/kataras/go-mailer"
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
// set a root for our templates
|
||||
app.Adapt(view.HTML("./templates", ".html"))
|
||||
|
||||
// change these to your own settings
|
||||
cfg := mailer.Config{
|
||||
Host: "smtp.mailgun.org",
|
||||
Username: "postmaster@sandbox661c307650f04e909150b37c0f3b2f09.mailgun.org",
|
||||
Password: "38304272b8ee5c176d5961dc155b2417",
|
||||
Port: 587,
|
||||
}
|
||||
// change these to your e-mail to check if that works
|
||||
|
||||
// create the service
|
||||
mailService := mailer.New(cfg)
|
||||
|
||||
var to = []string{"kataras2006@hotmail.com"}
|
||||
|
||||
// standalone
|
||||
|
||||
//mailService.Send("iris e-mail test subject", "</h1>outside of context before server's listen!</h1>", to...)
|
||||
|
||||
//inside handler
|
||||
app.Get("/send", func(ctx *iris.Context) {
|
||||
content := `<h1>Hello From Iris web framework</h1> <br/><br/> <span style="color:blue"> This is the rich message body </span>`
|
||||
|
||||
err := mailService.Send("iris e-mail just t3st subject", content, to...)
|
||||
|
||||
if err != nil {
|
||||
ctx.HTML(200, "<b> Problem while sending the e-mail: "+err.Error())
|
||||
} else {
|
||||
ctx.HTML(200, "<h1> SUCCESS </h1>")
|
||||
}
|
||||
})
|
||||
|
||||
// send a body by template
|
||||
app.Get("/send/template", func(ctx *iris.Context) {
|
||||
// we will not use ctx.Render
|
||||
// because we don't want to render to the client
|
||||
// we need the templates' parsed result as raw bytes
|
||||
// so we make use of the bytes.Buffer which is an io.Writer
|
||||
// which being expected on app.Render parameter first.
|
||||
//
|
||||
// the rest of the parameters are the same and the behavior is the same as ctx.Render,
|
||||
// except the 'where to render'
|
||||
buff := &bytes.Buffer{}
|
||||
|
||||
app.Render(buff, "body.html", iris.Map{
|
||||
"Message": " his is the rich message body sent by a template!!",
|
||||
"Footer": "The footer of this e-mail!",
|
||||
})
|
||||
content := buff.String()
|
||||
|
||||
err := mailService.Send("iris e-mail just t3st subject", content, to...)
|
||||
|
||||
if err != nil {
|
||||
ctx.HTML(iris.StatusOK, "<b> Problem while sending the e-mail: "+err.Error())
|
||||
} else {
|
||||
ctx.HTML(iris.StatusOK, "<h1> SUCCESS </h1>")
|
||||
}
|
||||
})
|
||||
app.Listen(":8080")
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
<h1>Hello From Iris web framework</h1>
|
||||
<br />
|
||||
<br />
|
||||
<span style="color: red"> {{.Message}}</span>
|
||||
<hr />
|
||||
|
||||
<b> {{.Footer}} </b>
|
||||
@@ -1,26 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
sess := sessions.New(sessions.Config{Cookie: "myappsessionid"})
|
||||
app.Adapt(sess)
|
||||
|
||||
app.Get("/set", func(ctx *iris.Context) {
|
||||
sess := sessions.New(sessions.Config{Cookie: "myappsessionid"})
|
||||
app.AttachSessionManager(sess)
|
||||
|
||||
app.Get("/set", func(ctx context.Context) {
|
||||
ctx.Session().SetFlash("name", "iris")
|
||||
ctx.Writef("Message setted, is available for the next request")
|
||||
})
|
||||
|
||||
app.Get("/get", func(ctx *iris.Context) {
|
||||
app.Get("/get", func(ctx context.Context) {
|
||||
name := ctx.Session().GetFlashString("name")
|
||||
if name == "" {
|
||||
ctx.Writef("Empty name!!")
|
||||
@@ -29,7 +27,7 @@ func main() {
|
||||
ctx.Writef("Hello %s", name)
|
||||
})
|
||||
|
||||
app.Get("/test", func(ctx *iris.Context) {
|
||||
app.Get("/test", func(ctx context.Context) {
|
||||
name := ctx.Session().GetFlashString("name")
|
||||
if name == "" {
|
||||
ctx.Writef("Empty name!!")
|
||||
@@ -41,5 +39,5 @@ func main() {
|
||||
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
stdContext "context"
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/host"
|
||||
)
|
||||
|
||||
// Before continue, please read the below notes:
|
||||
//
|
||||
// Current version of Iris is auto-graceful on control+C/command+C
|
||||
// or whenever host's .Shutdown called.
|
||||
//
|
||||
// In order to add a custom interrupt handler(ctrl+c/cmd+c) or
|
||||
// shutdown manually you have to "schedule a host supervisor's task" or
|
||||
// use the core/host package manually or use a pure http.Server as we already seen at "custom-server" example.
|
||||
//
|
||||
// At this example, we will disable the interrupt handler and set our own interrupt handler.
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML(" <h1>hi, I just exist in order to see if the server is closed</h1>")
|
||||
})
|
||||
|
||||
// tasks are always running in their go-routine by-default.
|
||||
//
|
||||
// register custom interrupt handler, fires when ctrl+C/cmd+C pressed.
|
||||
app.Scheduler.Schedule(host.OnInterrupt(func(proc host.TaskProcess) {
|
||||
println("Shutdown the server gracefully...")
|
||||
|
||||
timeout := 5 * time.Second // give the server 5 seconds to wait for idle connections.
|
||||
ctx, cancel := stdContext.WithTimeout(stdContext.Background(), timeout)
|
||||
defer cancel()
|
||||
proc.Host().Shutdown(ctx) // Shutdown the underline supervisor's server
|
||||
}))
|
||||
|
||||
// Start the server and disable the default interrupt handler in order to use our scheduled interrupt task.
|
||||
app.Run(iris.Addr(":8080"), iris.WithoutInterruptHandler)
|
||||
}
|
||||
|
||||
// Note:
|
||||
// You can just use an http.Handler with your own signal notify channel and do that as you did with the net/http
|
||||
// package. I will not show this way, but you can find many examples on the internet.
|
||||
@@ -0,0 +1,72 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
stdContext "context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/host"
|
||||
)
|
||||
|
||||
// The difference from its parent main.go is that
|
||||
// with a custom host we're able to call the host's shutdown
|
||||
// and be notified about its .Shutdown call.
|
||||
// Almost the same as before.
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML(" <h1>hi, I just exist in order to see if the server is closed</h1>")
|
||||
})
|
||||
|
||||
// build the framework when all routing-relative actions are declared.
|
||||
if err := app.Build(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// create our custom host supervisor by adapting
|
||||
// a custom http server
|
||||
srv := host.New(&http.Server{Addr: ":8080", Handler: app})
|
||||
|
||||
// tasks are always running in their go-routine by-default.
|
||||
//
|
||||
// register custom interrupt handler, fires when ctrl+C/cmd+C pressed, as we did before.
|
||||
srv.Schedule(host.OnInterrupt(func(proc host.TaskProcess) {
|
||||
println("Shutdown the server gracefully...")
|
||||
|
||||
timeout := 5 * time.Second // give the server 5 seconds to wait for idle connections.
|
||||
ctx, cancel := stdContext.WithTimeout(stdContext.Background(), timeout)
|
||||
defer cancel()
|
||||
proc.Host().DeferFlow() // defer the exit, in order to catch the event
|
||||
srv.Shutdown(ctx) // Shutdown the supervisor, only this way the proc.Host().Done will be notified
|
||||
// the proc.Host().Shutdown, closes the underline server but no the supervisor.
|
||||
// This behavior was choosen because is inneed for custom maintanance services
|
||||
// (i.e restart server every week without loosing connections) which you can easly adapt with Iris.
|
||||
}))
|
||||
|
||||
// schedule a task to be notify when the server was closed by our interrutp handler,
|
||||
// optionally ofcourse.
|
||||
srv.ScheduleFunc(func(proc host.TaskProcess) {
|
||||
select {
|
||||
case <-proc.Host().Done(): // when .Host.Shutdown(ctx) called.
|
||||
println("Server was closed.")
|
||||
proc.Host().RestoreFlow() // Restore the flow in order to exit(continue after the srv.ListenAndServe)
|
||||
}
|
||||
})
|
||||
|
||||
// Start our custom host
|
||||
println("Server is running at :8080")
|
||||
srv.ListenAndServe()
|
||||
// Go to the console and press ctrl+c(for windows and linux) or cmd+c for osx.
|
||||
// The output should be:
|
||||
// Server is running at:8080
|
||||
// Shutdown the server gracefully...
|
||||
// Server was closed.
|
||||
}
|
||||
|
||||
// Note:
|
||||
// You can just use an http.Handler with your own signal notify channel and do that as you did with the net/http
|
||||
// package. I will not show this way, but you can find many examples on the internet.
|
||||
@@ -1,32 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/hi", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, " <h1>hi, I just exist in order to see if the server is closed</h1>")
|
||||
})
|
||||
|
||||
app.Adapt(iris.EventPolicy{
|
||||
// Interrupt Event means when control+C pressed on terminal.
|
||||
Interrupted: func(*iris.Framework) {
|
||||
// shut down gracefully, but wait 5 seconds the maximum before closed
|
||||
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
app.Shutdown(ctx)
|
||||
},
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.AttachSessionManager(sessions.New(sessions.Config{Cookie: "mysessionid"}))
|
||||
|
||||
app.Get("/hello", func(ctx context.Context) {
|
||||
sess := ctx.Session()
|
||||
if !sess.HasFlash() {
|
||||
ctx.HTML("<h1> Unauthorized Page! </h1>")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(context.Map{
|
||||
"Message": "Hello",
|
||||
"From": sess.GetFlash("name"),
|
||||
})
|
||||
})
|
||||
|
||||
app.Post("/login", func(ctx context.Context) {
|
||||
sess := ctx.Session()
|
||||
if !sess.HasFlash() {
|
||||
sess.SetFlash("name", ctx.FormValue("name"))
|
||||
}
|
||||
|
||||
})
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris/httptest"
|
||||
)
|
||||
|
||||
// $ cd _example
|
||||
// $ go test -v
|
||||
func TestNewApp(t *testing.T) {
|
||||
app := newApp()
|
||||
e := httptest.New(app, t)
|
||||
|
||||
// test nauthorized
|
||||
e.GET("/hello").Expect().Status(401).Body().Equal("<h1> Unauthorized Page! </h1>")
|
||||
// test our login flash message
|
||||
name := "myname"
|
||||
e.POST("/login").WithFormField("name", name).Expect().Status(200)
|
||||
// test the /hello again with the flash (a message which deletes itself after it has been shown to the user)
|
||||
// setted on /login previously.
|
||||
expectedResponse := map[string]interface{}{
|
||||
"Message": "Hello",
|
||||
"From": name,
|
||||
}
|
||||
e.GET("/hello").Expect().Status(200).JSON().Equal(expectedResponse)
|
||||
// test /hello nauthorized again, it should be return 401 now (flash should be removed)
|
||||
e.GET("/hello").Expect().Status(401).Body().Equal("<h1> Unauthorized Page! </h1>")
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/i18n"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/middleware/i18n"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // adapt a simple internal logger to print any errors
|
||||
app.Adapt(httprouter.New()) // adapt a router, you can use gorillamux too
|
||||
|
||||
app.Use(i18n.New(i18n.Config{
|
||||
Default: "en-US",
|
||||
@@ -19,14 +17,14 @@ func main() {
|
||||
"el-GR": "./locales/locale_el-GR.ini",
|
||||
"zh-CN": "./locales/locale_zh-CN.ini"}}))
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
|
||||
// it tries to find the language by:
|
||||
// ctx.Get("language") , that should be setted on other middleware before the i18n middleware*
|
||||
// ctx.Values().GetString("language")
|
||||
// if that was empty then
|
||||
// it tries to find from the URLParameter setted on the configuration
|
||||
// if not found then
|
||||
// it tries to find the language by the "lang" cookie
|
||||
// it tries to find the language by the "language" cookie
|
||||
// if didn't found then it it set to the Default setted on the configuration
|
||||
|
||||
// hi is the key, 'kataras' is the %s on the .ini file
|
||||
@@ -36,7 +34,7 @@ func main() {
|
||||
// or:
|
||||
hi := i18n.Translate(ctx, "hi", "kataras")
|
||||
|
||||
language := ctx.Get(iris.TranslateLanguageContextKey) // language is the language key, example 'en-US'
|
||||
language := ctx.Values().GetString(ctx.Application().ConfigurationReadOnly().GetTranslateLanguageContextKey()) // return is form of 'en-US'
|
||||
|
||||
// The first succeed language found saved at the cookie with name ("language"),
|
||||
// you can change that by changing the value of the: iris.TranslateLanguageContextKey
|
||||
@@ -46,6 +44,6 @@ func main() {
|
||||
// go to http://localhost:8080/?lang=el-GR
|
||||
// or http://localhost:8080
|
||||
// or http://localhost:8080/?lang=zh-CN
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/pprof"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, "<h1> Please click <a href='/debug/pprof'>here</a>")
|
||||
})
|
||||
|
||||
app.Get("/debug/pprof/*action", pprof.New())
|
||||
// ___________
|
||||
// Note:
|
||||
// if you prefer gorillamux adaptor, then
|
||||
// the wildcard for gorilla mux (as you already know) is '{action:.*}' instead of '*action'.
|
||||
app.Listen(":8080")
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/recover"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// fast way to enable non-fatal messages to be printed to the user
|
||||
// (yes in iris even recover's errors are not fatal because it's restarting,
|
||||
// ProdMode messages are only for things that Iris cannot continue at all,
|
||||
// these are logged by-default but you can change that behavior too by passing a different LoggerPolicy to the .Adapt)
|
||||
app.Adapt(iris.DevLogger())
|
||||
// adapt a router, you can use gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
// use this recover(y) middleware
|
||||
app.Use(recover.New())
|
||||
|
||||
i := 0
|
||||
// let's simmilate a panic every next request
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
i++
|
||||
if i%2 == 0 {
|
||||
panic("a panic here")
|
||||
}
|
||||
ctx.Writef("Hello, refresh one time more to get panic!")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
app.Listen(":8080")
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/logger"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Adapt(iris.DevLogger()) // it just enables the print of the iris.DevMode logs. Enable it to view the middleware's messages.
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
customLogger := logger.New(logger.Config{
|
||||
// Status displays status code
|
||||
Status: true,
|
||||
// IP displays request's remote address
|
||||
IP: true,
|
||||
// Method displays the http method
|
||||
Method: true,
|
||||
// Path displays the request path
|
||||
Path: true,
|
||||
})
|
||||
|
||||
app.Use(customLogger)
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
app.Get("/1", func(ctx *iris.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
app.Get("/2", func(ctx *iris.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
// log http errors
|
||||
errorLogger := logger.New()
|
||||
|
||||
app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
|
||||
errorLogger.Serve(ctx)
|
||||
ctx.Writef("My Custom 404 error page ")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/1
|
||||
// http://localhost:8080/2
|
||||
app.Listen(":8080")
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
none, _ := app.None("/invisible/{username}", func(ctx context.Context) {
|
||||
ctx.Writef("Hello %s with method: %s", ctx.Values().GetString("username"), ctx.Method())
|
||||
|
||||
if from := ctx.Values().GetString("from"); from != "" {
|
||||
ctx.Writef("\nI see that you're coming from %s", from)
|
||||
}
|
||||
})
|
||||
|
||||
app.Get("/change", func(ctx context.Context) {
|
||||
|
||||
if none.IsOnline() {
|
||||
none.Method = iris.MethodNone
|
||||
} else {
|
||||
none.Method = iris.MethodGet
|
||||
}
|
||||
|
||||
// refresh re-builds the router at serve-time in order to be notified for its new routes.
|
||||
app.RefreshRouter()
|
||||
})
|
||||
|
||||
app.Get("/execute", func(ctx context.Context) {
|
||||
// same as navigating to "http://localhost:8080/invisible/kataras" when /change has being invoked and route state changed
|
||||
// from "offline" to "online"
|
||||
ctx.Values().Set("from", "/execute") // values and session can be shared when calling Exec from a "foreign" context.
|
||||
ctx.Exec("GET", "/invisible/kataras")
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 264 KiB |
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,43 @@
|
||||
// for templates + go-bindata checkout the '_examples\intermediate\view\embedding-templates-into-app' folder.
|
||||
package main
|
||||
|
||||
// First of all, execute: $ go get https://github.com/jteeuwen/go-bindata
|
||||
// Secondly, execute the command: cd $GOPATH/src/github.com/kataras/iris/_examples/intermediate/serve-embedded-files && go-bindata ./assets/...
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("<b> Hi from index</b>")
|
||||
})
|
||||
|
||||
// executing this go-bindata command creates a source file named 'bindata.go' which
|
||||
// gives you the Asset and AssetNames funcs which we will pass into .StaticAssets
|
||||
// for more viist: https://github.com/jteeuwen/go-bindata
|
||||
// Iris gives you a way to integrade these functions to your web app
|
||||
|
||||
// For the reason that you may use go-bindata to embed more than your assets,
|
||||
// you should pass the 'virtual directory path', for example here is the : "./assets"
|
||||
// and the request path, which these files will be served to,
|
||||
// you can set as "/assets" or "/static" which resulting on http://localhost:8080/static/*anyfile.*extension
|
||||
app.StaticEmbedded("/static", "./assets", Asset, AssetNames)
|
||||
|
||||
// that's all
|
||||
// this will serve the ./assets (embedded) files to the /static request path for example the favicon.ico will be served as :
|
||||
// http://localhost:8080/static/favicon.ico
|
||||
// Methods: GET and HEAD
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
// Navigate to:
|
||||
// http://localhost:8080/static/favicon.ico
|
||||
// http://localhost:8080/static/js/jquery-2.1.1.js
|
||||
// http://localhost:8080/static/css/bootstrap.min.css
|
||||
|
||||
// Now, these files are are stored into inside your executable program, no need to keep it in the same location with your assets folder.
|
||||
@@ -1,11 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions/sessiondb/redis"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions/sessiondb/redis/service"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/sessions"
|
||||
"github.com/kataras/iris/sessions/sessiondb/redis"
|
||||
"github.com/kataras/iris/sessions/sessiondb/redis/service"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -29,16 +30,16 @@ func main() {
|
||||
|
||||
// the rest of the code stays the same.
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
// enable all (error) logs
|
||||
// select the httprouter as the servemux
|
||||
|
||||
// Adapt the session manager we just created
|
||||
app.Adapt(mySessions)
|
||||
// Attach the session manager we just created
|
||||
app.AttachSessionManager(mySessions)
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
|
||||
})
|
||||
app.Get("/set", func(ctx *iris.Context) {
|
||||
app.Get("/set", func(ctx context.Context) {
|
||||
|
||||
//set session values
|
||||
ctx.Session().Set("name", "iris")
|
||||
@@ -47,27 +48,27 @@ func main() {
|
||||
ctx.Writef("All ok session setted to: %s", ctx.Session().GetString("name"))
|
||||
})
|
||||
|
||||
app.Get("/get", func(ctx *iris.Context) {
|
||||
app.Get("/get", func(ctx context.Context) {
|
||||
// get a specific key, as string, if no found returns just an empty string
|
||||
name := ctx.Session().GetString("name")
|
||||
|
||||
ctx.Writef("The name on the /set was: %s", name)
|
||||
})
|
||||
|
||||
app.Get("/delete", func(ctx *iris.Context) {
|
||||
app.Get("/delete", func(ctx context.Context) {
|
||||
// delete a specific key
|
||||
ctx.Session().Delete("name")
|
||||
})
|
||||
|
||||
app.Get("/clear", func(ctx *iris.Context) {
|
||||
app.Get("/clear", func(ctx context.Context) {
|
||||
// removes all entries
|
||||
ctx.Session().Clear()
|
||||
})
|
||||
|
||||
app.Get("/destroy", func(ctx *iris.Context) {
|
||||
app.Get("/destroy", func(ctx context.Context) {
|
||||
//destroy, removes the entire session data and cookie
|
||||
ctx.SessionDestroy()
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
var (
|
||||
key = "my_sessionid"
|
||||
)
|
||||
|
||||
func secret(ctx *iris.Context) {
|
||||
func secret(ctx context.Context) {
|
||||
|
||||
// Check if user is authenticated
|
||||
if auth, _ := ctx.Session().GetBoolean("authenticated"); !auth {
|
||||
ctx.EmitError(iris.StatusForbidden)
|
||||
ctx.StatusCode(iris.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -22,7 +23,7 @@ func secret(ctx *iris.Context) {
|
||||
ctx.WriteString("The cake is a lie!")
|
||||
}
|
||||
|
||||
func login(ctx *iris.Context) {
|
||||
func login(ctx context.Context) {
|
||||
session := ctx.Session()
|
||||
|
||||
// Authentication goes here
|
||||
@@ -32,7 +33,7 @@ func login(ctx *iris.Context) {
|
||||
session.Set("authenticated", true)
|
||||
}
|
||||
|
||||
func logout(ctx *iris.Context) {
|
||||
func logout(ctx context.Context) {
|
||||
session := ctx.Session()
|
||||
|
||||
// Revoke users authentication
|
||||
@@ -41,15 +42,15 @@ func logout(ctx *iris.Context) {
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
// Look https://github.com/kataras/iris/tree/v6/adaptors/sessions/_examples for more features,
|
||||
|
||||
// Look https://github.com/kataras/iris/tree/master/sessions/_examples for more features,
|
||||
// i.e encode/decode and lifetime.
|
||||
sess := sessions.New(sessions.Config{Cookie: key})
|
||||
app.Adapt(sess)
|
||||
app.AttachSessionManager(sess)
|
||||
|
||||
app.Get("/secret", secret)
|
||||
app.Get("/login", login)
|
||||
app.Get("/logout", logout)
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -5,15 +5,15 @@ import (
|
||||
// At this example we use the gorilla's securecookie library:
|
||||
"github.com/gorilla/securecookie"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
// enable all (error) logs
|
||||
// select the httprouter as the servemux
|
||||
|
||||
cookieName := "mycustomsessionid"
|
||||
// AES only supports key sizes of 16, 24 or 32 bytes.
|
||||
@@ -28,19 +28,17 @@ func main() {
|
||||
Decode: secureCookie.Decode,
|
||||
})
|
||||
|
||||
app.Adapt(mySessions)
|
||||
|
||||
// OPTIONALLY:
|
||||
// import "gopkg.in/kataras/iris.v6/adaptors/sessions/sessiondb/redis"
|
||||
// import "github.com/kataras/iris/sessions/sessiondb/redis"
|
||||
// or import "github.com/kataras/go-sessions/sessiondb/$any_available_community_database"
|
||||
// mySessions.UseDatabase(redis.New(...))
|
||||
|
||||
app.Adapt(mySessions) // Adapt the session manager we just created.
|
||||
app.AttachSessionManager(mySessions) // Attach the session manager we just created.
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
|
||||
})
|
||||
app.Get("/set", func(ctx *iris.Context) {
|
||||
app.Get("/set", func(ctx context.Context) {
|
||||
|
||||
//set session values
|
||||
ctx.Session().Set("name", "iris")
|
||||
@@ -49,24 +47,24 @@ func main() {
|
||||
ctx.Writef("All ok session setted to: %s", ctx.Session().GetString("name"))
|
||||
})
|
||||
|
||||
app.Get("/get", func(ctx *iris.Context) {
|
||||
app.Get("/get", func(ctx context.Context) {
|
||||
// get a specific key, as string, if no found returns just an empty string
|
||||
name := ctx.Session().GetString("name")
|
||||
|
||||
ctx.Writef("The name on the /set was: %s", name)
|
||||
})
|
||||
|
||||
app.Get("/delete", func(ctx *iris.Context) {
|
||||
app.Get("/delete", func(ctx context.Context) {
|
||||
// delete a specific key
|
||||
ctx.Session().Delete("name")
|
||||
})
|
||||
|
||||
app.Get("/clear", func(ctx *iris.Context) {
|
||||
app.Get("/clear", func(ctx context.Context) {
|
||||
// removes all entries
|
||||
ctx.Session().Clear()
|
||||
})
|
||||
|
||||
app.Get("/destroy", func(ctx *iris.Context) {
|
||||
app.Get("/destroy", func(ctx context.Context) {
|
||||
//destroy, removes the entire session data and cookie
|
||||
ctx.SessionDestroy()
|
||||
}) // Note about destroy:
|
||||
@@ -75,5 +73,5 @@ func main() {
|
||||
// mySessions.DestroyByID
|
||||
// mySessions.DestroyAll
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -3,15 +3,15 @@ package main
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
// enable all (error) logs
|
||||
// select the httprouter as the servemux
|
||||
|
||||
mySessions := sessions.New(sessions.Config{
|
||||
// Cookie string, the session's client cookie name, for example: "mysessionid"
|
||||
@@ -23,8 +23,6 @@ func main() {
|
||||
// -1 means expire when browser closes
|
||||
// or set a value, like 2 hours:
|
||||
Expires: time.Hour * 2,
|
||||
// the length of the sessionid's cookie's value
|
||||
CookieLength: 32,
|
||||
// if you want to invalid cookies on different subdomains
|
||||
// of the same host, then enable it
|
||||
DisableSubdomainPersistence: false,
|
||||
@@ -32,16 +30,16 @@ func main() {
|
||||
})
|
||||
|
||||
// OPTIONALLY:
|
||||
// import "gopkg.in/kataras/iris.v6/adaptors/sessions/sessiondb/redis"
|
||||
// import "github.com/kataras/iris/sessions/sessiondb/redis"
|
||||
// or import "github.com/kataras/go-sessions/sessiondb/$any_available_community_database"
|
||||
// mySessions.UseDatabase(redis.New(...))
|
||||
|
||||
app.Adapt(mySessions) // Adapt the session manager we just created.
|
||||
app.AttachSessionManager(mySessions) // Attach the session manager we just created.
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
|
||||
})
|
||||
app.Get("/set", func(ctx *iris.Context) {
|
||||
app.Get("/set", func(ctx context.Context) {
|
||||
|
||||
//set session values
|
||||
ctx.Session().Set("name", "iris")
|
||||
@@ -50,24 +48,24 @@ func main() {
|
||||
ctx.Writef("All ok session setted to: %s", ctx.Session().GetString("name"))
|
||||
})
|
||||
|
||||
app.Get("/get", func(ctx *iris.Context) {
|
||||
app.Get("/get", func(ctx context.Context) {
|
||||
// get a specific key, as string, if no found returns just an empty string
|
||||
name := ctx.Session().GetString("name")
|
||||
|
||||
ctx.Writef("The name on the /set was: %s", name)
|
||||
})
|
||||
|
||||
app.Get("/delete", func(ctx *iris.Context) {
|
||||
app.Get("/delete", func(ctx context.Context) {
|
||||
// delete a specific key
|
||||
ctx.Session().Delete("name")
|
||||
})
|
||||
|
||||
app.Get("/clear", func(ctx *iris.Context) {
|
||||
app.Get("/clear", func(ctx context.Context) {
|
||||
// removes all entries
|
||||
ctx.Session().Clear()
|
||||
})
|
||||
|
||||
app.Get("/destroy", func(ctx *iris.Context) {
|
||||
app.Get("/destroy", func(ctx context.Context) {
|
||||
|
||||
//destroy, removes the entire session data and cookie
|
||||
ctx.SessionDestroy()
|
||||
@@ -78,5 +76,5 @@ func main() {
|
||||
// mySessions.DestroyByID
|
||||
// mySessions.DestroyAll
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Copyright (c) 1993-2009 Microsoft Corp.
|
||||
#
|
||||
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
|
||||
#
|
||||
# This file contains the mappings of IP addresses to host names. Each
|
||||
# entry should be kept on an individual line. The IP address should
|
||||
# be placed in the first column followed by the corresponding host name.
|
||||
# The IP address and the host name should be separated by at least one
|
||||
# space.
|
||||
#
|
||||
# Additionally, comments (such as these) may be inserted on individual
|
||||
# lines or following the machine name denoted by a '#' symbol.
|
||||
#
|
||||
# For example:
|
||||
#
|
||||
# 102.54.94.97 rhino.acme.com # source server
|
||||
# 38.25.63.10 x.acme.com # x client host
|
||||
|
||||
# localhost name resolution is handled within DNS itself.
|
||||
127.0.0.1 localhost
|
||||
::1 localhost
|
||||
#-IRIS-For development machine, you have to configure your dns also for online, search google how to do it if you don't know
|
||||
|
||||
127.0.0.1 domain.local
|
||||
127.0.0.1 system.domain.local
|
||||
127.0.0.1 dashboard.domain.local
|
||||
|
||||
#-END IRIS-
|
||||
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
/*
|
||||
* Setup static files
|
||||
*/
|
||||
|
||||
app.StaticWeb("/assets", "./public/assets")
|
||||
app.StaticWeb("/upload_resources", "./public/upload_resources")
|
||||
|
||||
dashboard := app.Party("dashboard.")
|
||||
{
|
||||
dashboard.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("HEY FROM dashboard")
|
||||
})
|
||||
}
|
||||
system := app.Party("system.")
|
||||
{
|
||||
system.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("HEY FROM system")
|
||||
})
|
||||
}
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("HEY FROM frontend /")
|
||||
})
|
||||
// http://domain.local:80
|
||||
// http://dashboard.local
|
||||
// http://system.local
|
||||
// Make sure you prepend the "http" in your browser
|
||||
// because .local is a virtual domain we think to show case you
|
||||
// that you can declare any syntactical correct name as a subdomain in Iris.
|
||||
app.Run(iris.Addr("domain.local:80")) // for beginners: look ../hosts file
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.2 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 7.2 KiB |
@@ -0,0 +1,27 @@
|
||||
# Copyright (c) 1993-2009 Microsoft Corp.
|
||||
#
|
||||
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
|
||||
#
|
||||
# This file contains the mappings of IP addresses to host names. Each
|
||||
# entry should be kept on an individual line. The IP address should
|
||||
# be placed in the first column followed by the corresponding host name.
|
||||
# The IP address and the host name should be separated by at least one
|
||||
# space.
|
||||
#
|
||||
# Additionally, comments (such as these) may be inserted on individual
|
||||
# lines or following the machine name denoted by a '#' symbol.
|
||||
#
|
||||
# For example:
|
||||
#
|
||||
# 102.54.94.97 rhino.acme.com # source server
|
||||
# 38.25.63.10 x.acme.com # x client host
|
||||
|
||||
# localhost name resolution is handled within DNS itself.
|
||||
127.0.0.1 localhost
|
||||
::1 localhost
|
||||
#-IRIS-For development machine, you have to configure your dns also for online, search google how to do it if you don't know
|
||||
|
||||
127.0.0.1 mydomain.com
|
||||
127.0.0.1 admin.mydomain.com
|
||||
|
||||
#-END IRIS-
|
||||
@@ -0,0 +1,47 @@
|
||||
// Package main register static subdomains, simple as parties, check ./hosts if you use windows
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// subdomains works with all available routers, like other features too.
|
||||
|
||||
// no order, you can register subdomains at the end also.
|
||||
admin := app.Party("admin.")
|
||||
{
|
||||
// admin.mydomain.com
|
||||
admin.Get("/", func(c context.Context) {
|
||||
c.Writef("INDEX FROM admin.mydomain.com")
|
||||
})
|
||||
// admin.mydomain.com/hey
|
||||
admin.Get("/hey", func(c context.Context) {
|
||||
c.Writef("HEY FROM admin.mydomain.com/hey")
|
||||
})
|
||||
// admin.mydomain.com/hey2
|
||||
admin.Get("/hey2", func(c context.Context) {
|
||||
c.Writef("HEY SECOND FROM admin.mydomain.com/hey")
|
||||
})
|
||||
}
|
||||
|
||||
// mydomain.com/
|
||||
app.Get("/", func(c context.Context) {
|
||||
c.Writef("INDEX FROM no-subdomain hey")
|
||||
})
|
||||
|
||||
// mydomain.com/hey
|
||||
app.Get("/hey", func(c context.Context) {
|
||||
c.Writef("HEY FROM no-subdomain hey")
|
||||
})
|
||||
|
||||
// http://admin.mydomain.com
|
||||
// http://admin.mydomain.com/hey
|
||||
// http://admin.mydomain.com/hey2
|
||||
// http://mydomain.com
|
||||
// http://mydomain.com/hey
|
||||
app.Run(iris.Addr("mydomain.com:80")) // for beginners: look ../hosts file
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
# Copyright (c) 1993-2009 Microsoft Corp.
|
||||
#
|
||||
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
|
||||
#
|
||||
# This file contains the mappings of IP addresses to host names. Each
|
||||
# entry should be kept on an individual line. The IP address should
|
||||
# be placed in the first column followed by the corresponding host name.
|
||||
# The IP address and the host name should be separated by at least one
|
||||
# space.
|
||||
#
|
||||
# Additionally, comments (such as these) may be inserted on individual
|
||||
# lines or following the machine name denoted by a '#' symbol.
|
||||
#
|
||||
# For example:
|
||||
#
|
||||
# 102.54.94.97 rhino.acme.com # source server
|
||||
# 38.25.63.10 x.acme.com # x client host
|
||||
|
||||
# localhost name resolution is handled within DNS itself.
|
||||
127.0.0.1 localhost
|
||||
::1 localhost
|
||||
#-IRIS-For development machine, you have to configure your dns also for online, search google how to do it if you don't know
|
||||
127.0.0.1 mydomain.com
|
||||
127.0.0.1 username1.mydomain.com
|
||||
127.0.0.1 username2.mydomain.com
|
||||
127.0.0.1 username3.mydomain.com
|
||||
127.0.0.1 username4.mydomain.com
|
||||
127.0.0.1 username5.mydomain.com
|
||||
|
||||
#-END IRIS-
|
||||
@@ -0,0 +1,72 @@
|
||||
// Package main an example on how to catch dynamic subdomains - wildcard.
|
||||
// On the first example (subdomains_1) we saw how to create routes for static subdomains, subdomains you know that you will have.
|
||||
// Here we will see an example how to catch unknown subdomains, dynamic subdomains, like username.mydomain.com:8080.
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
// register a dynamic-wildcard subdomain to your server machine(dns/...) first, check ./hosts if you use windows.
|
||||
// run this file and try to redirect: http://username1.mydomain.com:8080/ , http://username2.mydomain.com:8080/ , http://username1.mydomain.com/something, http://username1.mydomain.com/something/sadsadsa
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
/* Keep note that you can use both type of subdomains (named and wildcard(*.) )
|
||||
admin.mydomain.com, and for other the Party(*.) but this is not this example's purpose
|
||||
|
||||
admin := app.Party("admin.")
|
||||
{
|
||||
// admin.mydomain.com
|
||||
admin.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("INDEX FROM admin.mydomain.com")
|
||||
})
|
||||
// admin.mydomain.com/hey
|
||||
admin.Get("/hey", func(ctx context.Context) {
|
||||
ctx.Writef("HEY FROM admin.mydomain.com/hey")
|
||||
})
|
||||
// admin.mydomain.com/hey2
|
||||
admin.Get("/hey2", func(ctx context.Context) {
|
||||
ctx.Writef("HEY SECOND FROM admin.mydomain.com/hey")
|
||||
})
|
||||
}*/
|
||||
|
||||
// no order, you can register subdomains at the end also.
|
||||
dynamicSubdomains := app.Party("*.")
|
||||
{
|
||||
dynamicSubdomains.Get("/", dynamicSubdomainHandler)
|
||||
|
||||
dynamicSubdomains.Get("/something", dynamicSubdomainHandler)
|
||||
|
||||
dynamicSubdomains.Get("/something/{paramfirst}", dynamicSubdomainHandlerWithParam)
|
||||
}
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from mydomain.com path: %s", ctx.Path())
|
||||
})
|
||||
|
||||
app.Get("/hello", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from mydomain.com path: %s", ctx.Path())
|
||||
})
|
||||
|
||||
// http://mydomain.com:8080
|
||||
// http://username1.mydomain.com:8080
|
||||
// http://username2.mydomain.com:8080/something
|
||||
// http://username3.mydomain.com:8080/something/yourname
|
||||
app.Run(iris.Addr("mydomain.com:8080")) // for beginners: look ../hosts file
|
||||
}
|
||||
|
||||
func dynamicSubdomainHandler(ctx context.Context) {
|
||||
username := ctx.Subdomain()
|
||||
ctx.Writef("Hello from dynamic subdomain path: %s, here you can handle the route for dynamic subdomains, handle the user: %s", ctx.Path(), username)
|
||||
// if http://username4.mydomain.com:8080/ prints:
|
||||
// Hello from dynamic subdomain path: /, here you can handle the route for dynamic subdomains, handle the user: username4
|
||||
}
|
||||
|
||||
func dynamicSubdomainHandlerWithParam(ctx context.Context) {
|
||||
username := ctx.Subdomain()
|
||||
ctx.Writef("Hello from dynamic subdomain path: %s, here you can handle the route for dynamic subdomains, handle the user: %s", ctx.Path(), username)
|
||||
ctx.Writef("The paramfirst is: %s", ctx.Params().Get("paramfirst"))
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// subdomains works with all available routers, like other features too.
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.BeginTransaction(func(t *context.Transaction) {
|
||||
// OPTIONAl STEP: , if true then the next transictions will not be executed if this transiction fails
|
||||
// t.SetScope(context.RequestTransactionScope)
|
||||
|
||||
// OPTIONAL STEP:
|
||||
// create a new custom type of error here to keep track of the status code and reason message
|
||||
err := context.NewTransactionErrResult()
|
||||
|
||||
// we should use t.Context if we want to rollback on any errors lives inside this function clojure.
|
||||
t.Context().Text("Blablabla this should not be sent to the client because we will fill the err with a message and status")
|
||||
|
||||
// virtualize a fake error here, for the shake of the example
|
||||
fail := true
|
||||
if fail {
|
||||
err.StatusCode = iris.StatusInternalServerError
|
||||
// NOTE: if empty reason then the default or the custom http error will be fired (like ctx.FireStatusCode)
|
||||
err.Reason = "Error: Virtual failure!!"
|
||||
}
|
||||
|
||||
// OPTIONAl STEP:
|
||||
// but useful if we want to post back an error message to the client if the transaction failed.
|
||||
// if the reason is empty then the transaction completed succesfuly,
|
||||
// otherwise we rollback the whole response writer's body,
|
||||
// headers and cookies, status code and everything lives inside this transaction
|
||||
t.Complete(err)
|
||||
})
|
||||
|
||||
ctx.BeginTransaction(func(t *context.Transaction) {
|
||||
t.Context().HTML("<h1>This will sent at all cases because it lives on different transaction and it doesn't fails</h1>")
|
||||
// * if we don't have any 'throw error' logic then no need of scope.Complete()
|
||||
})
|
||||
|
||||
// OPTIONALLY, depends on the usage:
|
||||
// at any case, what ever happens inside the context's transactions send this to the client
|
||||
ctx.HTML("<h1>Let's add a second html message to the response, " +
|
||||
"if the transaction was failed and it was request scoped then this message would " +
|
||||
"not been shown. But it has a transient scope(default) so, it is visible as expected!</h1>")
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/typescript"
|
||||
)
|
||||
|
||||
// NOTE: Some machines don't allow to install typescript automatically, so if you don't have typescript installed
|
||||
// and the typescript adaptor doesn't works for you then follow the below steps:
|
||||
// 1. close the iris server
|
||||
// 2. open your terminal and execute: npm install -g typescript
|
||||
// 3. start your iris server, it should be work, as expected, now.
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
ts := typescript.New()
|
||||
ts.Config.Dir = "./www/scripts"
|
||||
ts.Attach(app) // attach the application to the typescript compiler
|
||||
|
||||
app.StaticWeb("/", "./www") // serve the index.html
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
// open http://localhost:8080
|
||||
// go to ./www/scripts/app.ts
|
||||
// make a change
|
||||
// reload the http://localhost:8080 and you should see the changes
|
||||
//
|
||||
// what it does?
|
||||
// - compiles the typescript files using default compiler options if not tsconfig found
|
||||
// - watches for changes on typescript files, if a change then it recompiles the .ts to .js
|
||||
//
|
||||
// same as you used to do with gulp-like tools, but here at Iris I do my bests to help GO developers.
|
||||
@@ -0,0 +1,8 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Load my script (lawl)</title>
|
||||
</head>
|
||||
<body>
|
||||
<script src="scripts/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
class User{
|
||||
private name: string;
|
||||
|
||||
constructor(fullname:string) {
|
||||
this.name = fullname;
|
||||
}
|
||||
|
||||
Hi(msg: string): string {
|
||||
return msg + " "+ this.name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
var user = new User("kataras");
|
||||
var hi = user.Hi("Hello");
|
||||
window.alert(hi);
|
||||
@@ -1,69 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
app.Adapt(view.HTML("./templates", ".html"))
|
||||
|
||||
// Serve the form.html to the user
|
||||
app.Get("/upload", func(ctx *iris.Context) {
|
||||
//create a token (optionally)
|
||||
|
||||
now := time.Now().Unix()
|
||||
h := md5.New()
|
||||
io.WriteString(h, strconv.FormatInt(now, 10))
|
||||
token := fmt.Sprintf("%x", h.Sum(nil))
|
||||
//render the form with the token for any use you like
|
||||
ctx.Render("upload_form.html", token)
|
||||
})
|
||||
|
||||
// Handle the post request from the upload_form.html to the server
|
||||
app.Post("/upload", iris.LimitRequestBodySize(10<<20),
|
||||
func(ctx *iris.Context) {
|
||||
// or use ctx.SetMaxRequestBodySize(10 << 20)
|
||||
//to limit the uploaded file(s) size.
|
||||
|
||||
// Get the file from the request
|
||||
file, info, err := ctx.FormFile("uploadfile")
|
||||
|
||||
if err != nil {
|
||||
ctx.HTML(iris.StatusInternalServerError,
|
||||
"Error while uploading: <b>"+err.Error()+"</b>")
|
||||
return
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
fname := info.Filename
|
||||
|
||||
// Create a file with the same name
|
||||
// assuming that you have a folder named 'uploads'
|
||||
out, err := os.OpenFile("./uploads/"+fname,
|
||||
os.O_WRONLY|os.O_CREATE, 0666)
|
||||
|
||||
if err != nil {
|
||||
ctx.HTML(iris.StatusInternalServerError,
|
||||
"Error while uploading: <b>"+err.Error()+"</b>")
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
io.Copy(out, file)
|
||||
})
|
||||
|
||||
// start the server at 127.0.0.1:8080
|
||||
app.Listen(":8080")
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Upload file</title>
|
||||
</head>
|
||||
<body>
|
||||
<form enctype="multipart/form-data"
|
||||
action="http://127.0.0.1:8080/upload" method="post">
|
||||
<input type="file" name="uploadfile" /> <input type="hidden"
|
||||
name="token" value="{{.}}" /> <input type="submit" value="upload" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -7,9 +7,9 @@ package main
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -20,39 +20,42 @@ const (
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
// set the view engine target to ./templates folder
|
||||
app.Adapt(view.HTML("./templates", ".html").Reload(true))
|
||||
|
||||
app.UseFunc(func(ctx *iris.Context) {
|
||||
// set the view engine target to ./templates folder
|
||||
app.AttachView(view.HTML("./templates", ".html").Reload(true))
|
||||
|
||||
app.Use(func(ctx context.Context) {
|
||||
// set the title, current time and a layout in order to be used if and when the next handler(s) calls the .Render function
|
||||
ctx.ViewData("Title", DefaultTitle)
|
||||
now := time.Now().Format(app.Config.TimeFormat)
|
||||
now := time.Now().Format(ctx.Application().ConfigurationReadOnly().GetTimeFormat())
|
||||
ctx.ViewData("CurrentTime", now)
|
||||
ctx.ViewLayout(DefaultLayout)
|
||||
|
||||
ctx.Next()
|
||||
})
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.ViewData("BodyMessage", "a sample text here... setted by the route handler")
|
||||
if err := ctx.Render("index.html", nil); err != nil {
|
||||
app.Log(iris.DevMode, err.Error())
|
||||
if err := ctx.View("index.html"); err != nil {
|
||||
ctx.Application().Log(err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
app.Get("/about", func(ctx *iris.Context) {
|
||||
app.Get("/about", func(ctx context.Context) {
|
||||
ctx.ViewData("Title", "My About Page")
|
||||
ctx.ViewData("BodyMessage", "about text here... setted by the route handler")
|
||||
|
||||
// same file, just to keep things simple.
|
||||
if err := ctx.Render("index.html", nil); err != nil {
|
||||
app.Log(iris.DevMode, err.Error())
|
||||
if err := ctx.View("index.html"); err != nil {
|
||||
ctx.Application().Log(err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
// Open localhost:8080 and localhost:8080/about
|
||||
app.Listen(":8080")
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/about
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
// Notes: ViewData("", myCustomStruct{}) will set this myCustomStruct value as a root binding data,
|
||||
// so any View("other", "otherValue") will probably fail.
|
||||
// To clear the binding data: ctx.Set(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey(), nil)
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
// Custom Render Policy to override or create new content-type render
|
||||
// i,e: "text/html" with a prefix,
|
||||
// we will just write to the writer and return false
|
||||
// to continue to the next contentType-matched renderer if any.
|
||||
app.Adapt(iris.RenderPolicy(func(out io.Writer, contentType string, binding interface{}, options ...map[string]interface{}) (bool, error) {
|
||||
|
||||
if contentType == "text/html" {
|
||||
if content, ok := binding.(string); ok {
|
||||
out.Write([]byte("<pre>My Custom prefix</pre><br/>" + content))
|
||||
}
|
||||
|
||||
}
|
||||
// continue to the next, no error
|
||||
// note: if we wanted to stop here we would return true instead of false.
|
||||
return false, nil
|
||||
}))
|
||||
|
||||
app.Get("", func(ctx *iris.Context) {
|
||||
|
||||
// These content-types are not managed by our RenderPolicy:
|
||||
// text, binary and html content-types are
|
||||
// not rendered via serializers, you have to
|
||||
// use the ctx.Render functions instead.
|
||||
// so something like this:
|
||||
// ctx.Text(iris.StatusOK, "my text content body here!")
|
||||
// will NOT work with out custom render policy.
|
||||
ctx.Render("text/html",
|
||||
"my text content body here!")
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
// templates/hi.html
|
||||
// DO NOT EDIT!
|
||||
|
||||
// NOTE: execute your own look main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -69,7 +68,7 @@ func (fi bindataFileInfo) Sys() interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
var _templatesHiHtml = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xb2\xc9\x28\xc9\xcd\xb1\xe3\xe5\xb2\xc9\x48\x4d\x4c\x01\xd1\x25\x99\x25\x39\xa9\x76\x1e\x99\x0a\x9e\x45\x99\xc5\x0a\xd1\x21\x1e\xae\x0a\x21\x9e\x21\x3e\xae\xb1\x36\xfa\x10\x29\xa0\x1a\x7d\x98\xe2\xa4\xfc\x94\x4a\x20\xcd\x69\x93\x61\x08\xd2\x52\x5d\xad\xe7\x97\x98\x9b\x5a\x5b\x0b\x52\x03\x95\x03\x2a\x86\xd8\x00\x08\x00\x00\xff\xff\xed\x0e\xad\x42\x6a\x00\x00\x00")
|
||||
var _templatesHiHtml = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xb2\xc9\x28\xc9\xcd\xb1\xe3\xe5\xb2\xc9\x48\x4d\x4c\x01\xd1\x25\x99\x25\x39\xa9\x76\xd5\xd5\x7a\x21\x20\x46\x6d\xad\x8d\x3e\x44\x84\x97\xcb\x46\x1f\xa6\x26\x29\x3f\xa5\xd2\x8e\x97\x8b\xd3\x26\xc3\xd0\xce\x23\x53\xa1\xba\x5a\xcf\x2f\x31\x37\xb5\xb6\x16\xa4\x06\x2a\x67\xa3\x0f\x35\x18\x10\x00\x00\xff\xff\x61\x88\xba\x25\x61\x00\x00\x00")
|
||||
|
||||
func templatesHiHtmlBytes() ([]byte, error) {
|
||||
return bindataRead(
|
||||
@@ -84,7 +83,7 @@ func templatesHiHtml() (*asset, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := bindataFileInfo{name: "templates/hi.html", size: 106, mode: os.FileMode(438), modTime: time.Unix(1487682349, 0)}
|
||||
info := bindataFileInfo{name: "templates/hi.html", size: 97, mode: os.FileMode(438), modTime: time.Unix(1496244983, 0)}
|
||||
a := &asset{bytes: bytes, info: info}
|
||||
return a, nil
|
||||
}
|
||||
@@ -185,8 +184,8 @@ type bintree struct {
|
||||
}
|
||||
|
||||
var _bintree = &bintree{nil, map[string]*bintree{
|
||||
"templates": &bintree{nil, map[string]*bintree{
|
||||
"hi.html": &bintree{templatesHiHtml, map[string]*bintree{}},
|
||||
"templates": {nil, map[string]*bintree{
|
||||
"hi.html": {templatesHiHtml, map[string]*bintree{}},
|
||||
}},
|
||||
}}
|
||||
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
// $ go get -u github.com/jteeuwen/go-bindata/...
|
||||
// $ go-bindata ./templates/...
|
||||
// $ go build
|
||||
// $ ./template_binary
|
||||
// templates are not used, you can delete the folder and run the example
|
||||
app.Adapt(view.HTML("./templates", ".html").Binary(Asset, AssetNames))
|
||||
app.Get("/hi", hi)
|
||||
app.Listen(":8080")
|
||||
// $ ./embedding-templates-into-app
|
||||
// html files are not used, you can delete the folder and run the example
|
||||
app.AttachView(view.HTML("./templates", ".html").Binary(Asset, AssetNames))
|
||||
app.Get("/", hi)
|
||||
|
||||
// http://localhost:8080
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func hi(ctx *iris.Context) {
|
||||
ctx.MustRender("hi.html", struct{ Name string }{Name: "iris"})
|
||||
type page struct {
|
||||
Title, Name string
|
||||
}
|
||||
|
||||
func hi(ctx context.Context) {
|
||||
ctx.ViewData("", page{Title: "Hi Page", Name: "iris"})
|
||||
ctx.View("hi.html")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Hi Iris [THE TITLE]</title>
|
||||
<title>{{.Title}}</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hi {{.Name}}
|
||||
|
||||
@@ -3,9 +3,9 @@ package main
|
||||
import (
|
||||
"encoding/xml"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/gorillamux"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
// ExampleXML just a test struct to view represents xml content-type
|
||||
@@ -17,43 +17,61 @@ type ExampleXML struct {
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(gorillamux.New())
|
||||
|
||||
app.Get("/data", func(ctx *iris.Context) {
|
||||
ctx.Data(iris.StatusOK, []byte("Some binary data here."))
|
||||
// Just some general restful render types, none of these has to do anything with templates.
|
||||
app.Get("/binary", func(ctx context.Context) { // useful when you want force-download of contents of raw bytes form.
|
||||
ctx.Binary([]byte("Some binary data here."))
|
||||
})
|
||||
|
||||
app.Get("/text", func(ctx *iris.Context) {
|
||||
ctx.Text(iris.StatusOK, "Plain text here")
|
||||
app.Get("/text", func(ctx context.Context) {
|
||||
ctx.Text("Plain text here")
|
||||
})
|
||||
|
||||
app.Get("/json", func(ctx *iris.Context) {
|
||||
ctx.JSON(iris.StatusOK, map[string]string{"hello": "json"}) // or myjsonStruct{hello:"json}
|
||||
app.Get("/json", func(ctx context.Context) {
|
||||
ctx.JSON(map[string]string{"hello": "json"}) // or myjsonStruct{hello:"json}
|
||||
})
|
||||
|
||||
app.Get("/jsonp", func(ctx *iris.Context) {
|
||||
ctx.JSONP(iris.StatusOK, "callbackName", map[string]string{"hello": "jsonp"})
|
||||
app.Get("/jsonp", func(ctx context.Context) {
|
||||
ctx.JSONP(map[string]string{"hello": "jsonp"}, context.JSONP{Callback: "callbackName"})
|
||||
})
|
||||
|
||||
app.Get("/xml", func(ctx *iris.Context) {
|
||||
ctx.XML(iris.StatusOK, ExampleXML{One: "hello", Two: "xml"}) // or iris.Map{"One":"hello"...}
|
||||
app.Get("/xml", func(ctx context.Context) {
|
||||
ctx.XML(ExampleXML{One: "hello", Two: "xml"}) // or context.Map{"One":"hello"...}
|
||||
})
|
||||
|
||||
app.Get("/markdown", func(ctx *iris.Context) {
|
||||
ctx.Markdown(iris.StatusOK, "# Hello Dynamic Markdown Iris")
|
||||
app.Get("/markdown", func(ctx context.Context) {
|
||||
ctx.Markdown([]byte("# Hello Dynamic Markdown -- Iris"))
|
||||
})
|
||||
|
||||
app.Adapt(view.HTML("./templates", ".html"))
|
||||
app.Get("/template", func(ctx *iris.Context) {
|
||||
//
|
||||
|
||||
ctx.MustRender(
|
||||
"hi.html", // the file name of the template relative to the './templates'
|
||||
iris.Map{"Name": "Iris"}, // the .Name inside the ./templates/hi.html
|
||||
iris.Map{"gzip": false}, // enable gzip for big files
|
||||
)
|
||||
// - standard html | view.HTML(...)
|
||||
// - django | view.Django(...)
|
||||
// - pug(jade) | view.Pug(...)
|
||||
// - handlebars | view.Handlebars(...)
|
||||
// - amber | view.Amber(...)
|
||||
// with default template funcs:
|
||||
//
|
||||
// - {{ urlpath "mynamedroute" "pathParameter_ifneeded" }}
|
||||
// - {{ render "header.html" }}
|
||||
// - {{ render_r "header.html" }} // partial relative path to current page
|
||||
// - {{ yield }}
|
||||
// - {{ current }}
|
||||
app.AttachView(view.HTML("./templates", ".html"))
|
||||
app.Get("/template", func(ctx context.Context) {
|
||||
|
||||
ctx.ViewData("Name", "Iris") // the .Name inside the ./templates/hi.html
|
||||
ctx.Gzip(true) // enable gzip for big files
|
||||
ctx.View("hi.html") // render the template with the file name relative to the './templates'
|
||||
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
// http://localhost:8080/binary
|
||||
// http://localhost:8080/text
|
||||
// http://localhost:8080/json
|
||||
// http://localhost:8080/jsonp
|
||||
// http://localhost:8080/xml
|
||||
// http://localhost:8080/markdown
|
||||
// http://localhost:8080/template
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -1,23 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New(iris.Configuration{Gzip: false, Charset: "UTF-8"}) // defaults to these
|
||||
app := iris.New() // defaults to these
|
||||
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
// - standard html | view.HTML(...)
|
||||
// - django | view.Django(...)
|
||||
// - pug(jade) | view.Pug(...)
|
||||
// - handlebars | view.Handlebars(...)
|
||||
// - amber | view.Amber(...)
|
||||
|
||||
app.Adapt(view.HTML("./templates", ".html"))
|
||||
tmpl := view.HTML("./templates", ".html")
|
||||
tmpl.Reload(true) // reload templates on each request (development mode)
|
||||
// default template funcs are:
|
||||
//
|
||||
// - {{ urlpath "mynamedroute" "pathParameter_ifneeded" }}
|
||||
// - {{ render "header.html" }}
|
||||
// - {{ render_r "header.html" }} // partial relative path to current page
|
||||
// - {{ yield }}
|
||||
// - {{ current }}
|
||||
tmpl.AddFunc("greet", func(s string) string {
|
||||
return "Greetings " + s + "!"
|
||||
})
|
||||
app.AttachView(tmpl)
|
||||
|
||||
app.Get("/hi", hi)
|
||||
app.Listen(":8080")
|
||||
app.Get("/", hi)
|
||||
|
||||
// http://localhost:8080
|
||||
app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8")) // defaults to that but you can change it.
|
||||
}
|
||||
|
||||
func hi(ctx *iris.Context) {
|
||||
ctx.MustRender("hi.html", struct{ Name string }{Name: "iris"})
|
||||
func hi(ctx context.Context) {
|
||||
ctx.ViewData("Title", "Hi Page")
|
||||
ctx.ViewData("Name", "Iris") // {{.Name}} will render: Iris
|
||||
// ctx.ViewData("", myCcustomStruct{})
|
||||
ctx.View("hi.html")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Hi Iris</title>
|
||||
<title>{{.Title}}</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hi {{.Name}} </h1>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
type mypage struct {
|
||||
@@ -13,20 +13,19 @@ type mypage struct {
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
tmpl := view.HTML("./templates", ".html")
|
||||
tmpl.Layout("layout.html")
|
||||
app.AttachView(view.HTML("./templates", ".html").Layout("layout.html"))
|
||||
// TIP: append .Reload(true) to reload the templates on each request.
|
||||
|
||||
app.Adapt(tmpl)
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Render("mypage.html", mypage{"My Page title", "Hello world!"}, iris.Map{"gzip": true})
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Gzip(true)
|
||||
ctx.ViewData("", mypage{"My Page title", "Hello world!"})
|
||||
ctx.View("mypage.html")
|
||||
// Note that: you can pass "layout" : "otherLayout.html" to bypass the config's Layout property
|
||||
// or iris.NoLayout to disable layout on this render action.
|
||||
// or view.NoLayout to disable layout on this render action.
|
||||
// third is an optional parameter
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
// http://localhost:8080
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<h1>Body is:</h1>
|
||||
<h1>[layout] Body content is below...</h1>
|
||||
<!-- Render the current template here -->
|
||||
{{ yield }}
|
||||
</body>
|
||||
|
||||
@@ -1,49 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
tmpl := view.HTML("./templates", ".html")
|
||||
tmpl.Layout("layouts/layout.html")
|
||||
tmpl.Funcs(map[string]interface{}{
|
||||
"greet": func(s string) string {
|
||||
return "Greetings " + s + "!"
|
||||
},
|
||||
tmpl.AddFunc("greet", func(s string) string {
|
||||
return "Greetings " + s + "!"
|
||||
})
|
||||
|
||||
app.Adapt(tmpl)
|
||||
app.AttachView(tmpl)
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
if err := ctx.Render("page1.html", nil); err != nil {
|
||||
println(err.Error())
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
if err := ctx.View("page1.html"); err != nil {
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.Writef(err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
// remove the layout for a specific route
|
||||
app.Get("/nolayout", func(ctx *iris.Context) {
|
||||
if err := ctx.Render("page1.html", nil, iris.RenderOptions{"layout": iris.NoLayout}); err != nil {
|
||||
println(err.Error())
|
||||
app.Get("/nolayout", func(ctx context.Context) {
|
||||
ctx.ViewLayout(view.NoLayout)
|
||||
if err := ctx.View("page1.html"); err != nil {
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.Writef(err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
// set a layout for a party, .Layout should be BEFORE any Get or other Handle party's method
|
||||
my := app.Party("/my").Layout("layouts/mylayout.html")
|
||||
{
|
||||
my.Get("/", func(ctx *iris.Context) {
|
||||
ctx.MustRender("page1.html", nil)
|
||||
{ // both of these will use the layouts/mylayout.html as their layout.
|
||||
my.Get("/", func(ctx context.Context) {
|
||||
ctx.View("page1.html")
|
||||
})
|
||||
my.Get("/other", func(ctx *iris.Context) {
|
||||
ctx.MustRender("page1.html", nil)
|
||||
my.Get("/other", func(ctx context.Context) {
|
||||
ctx.View("page1.html")
|
||||
})
|
||||
}
|
||||
|
||||
app.Listen(":8080")
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/nolayout
|
||||
// http://localhost:8080/my
|
||||
// http://localhost:8080/my/other
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -1,103 +1,75 @@
|
||||
// Package main an example on how to naming your routes & use the custom 'url' HTML Template Engine, same for other template engines.
|
||||
// Package main an example on how to naming your routes & use the custom 'url path' HTML Template Engine, same for other template engines.
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/gorillamux"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(view.HTML("./templates", ".html").Reload(true))
|
||||
if err := app.AttachView(view.HTML("./templates", ".html").Reload(true)); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
startWithHTTPRouter(app)
|
||||
// or uncomment
|
||||
// startWithGorillamux()
|
||||
mypathRoute, _ := app.Get("/mypath", writePathHandler)
|
||||
mypathRoute.Name = "my-page1"
|
||||
|
||||
app.Listen("localhost:8080")
|
||||
mypath2Route, err := app.Get("/mypath2/{paramfirst}/{paramsecond}", writePathHandler)
|
||||
// same as: app.Get("/mypath2/:paramfirst/:paramsecond", writePathHandler)
|
||||
if err != nil { // catch errors when creating a route or catch them on err := .Run, it's up to you.
|
||||
panic(err)
|
||||
}
|
||||
mypath2Route.Name = "my-page2"
|
||||
|
||||
mypath3Route, _ := app.Get("/mypath3/{paramfirst}/statichere/{paramsecond}", writePathHandler)
|
||||
mypath3Route.Name = "my-page3"
|
||||
|
||||
mypath4Route, _ := app.Get("/mypath4/{paramfirst}/statichere/{paramsecond}/{otherparam}/{something:path}", writePathHandler)
|
||||
// same as: app.Get("/mypath4/:paramfirst/statichere/:paramsecond/:otherparam/*something", writePathHandler)
|
||||
mypath4Route.Name = "my-page4"
|
||||
|
||||
// same with Handle/Func
|
||||
mypath5Route, _ := app.Handle("GET", "/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{something:path}", writePathHandler)
|
||||
mypath5Route.Name = "my-page5"
|
||||
|
||||
mypath6Route, _ := app.Get("/mypath6/{paramfirst}/{paramsecond}/statichere/{paramThirdAfterStatic}", writePathHandler)
|
||||
mypath6Route.Name = "my-page6"
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
// for /mypath6...
|
||||
paramsAsArray := []string{"theParam1", "theParam2", "paramThirdAfterStatic"}
|
||||
ctx.ViewData("ParamsAsArray", paramsAsArray)
|
||||
if err := ctx.View("page.html"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
})
|
||||
|
||||
app.Get("/redirect/{namedRoute}", func(ctx context.Context) {
|
||||
routeName := ctx.Params().Get("namedRoute")
|
||||
r := app.GetRoute(routeName)
|
||||
if r == nil {
|
||||
ctx.StatusCode(404)
|
||||
ctx.Writef("Route with name %s not found", routeName)
|
||||
return
|
||||
}
|
||||
|
||||
println("The path of " + routeName + "is: " + r.Path)
|
||||
// if routeName == "my-page1"
|
||||
// prints: The path of of my-page1 is: /mypath
|
||||
// if it's a path which takes named parameters
|
||||
// then use "r.ResolvePath(paramValuesHere)"
|
||||
ctx.Redirect(r.Path)
|
||||
// http://localhost:8080/redirect/my-page1 will redirect to -> http://localhost:8080/mypath
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost/redirect/my-page1
|
||||
app.Run(iris.Addr(":8080"))
|
||||
|
||||
}
|
||||
|
||||
func writePathHandler(ctx *iris.Context) {
|
||||
func writePathHandler(ctx context.Context) {
|
||||
ctx.Writef("Hello from %s.", ctx.Path())
|
||||
}
|
||||
|
||||
func startWithHTTPRouter(app *iris.Framework) {
|
||||
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/mypath", writePathHandler).ChangeName("my-page1")
|
||||
app.Get("/mypath2/:param1/:param2", writePathHandler).ChangeName("my-page2")
|
||||
app.Get("/mypath3/:param1/statichere/:param2", writePathHandler).ChangeName("my-page3")
|
||||
app.Get("/mypath4/:param1/statichere/:param2/:otherparam/*something", writePathHandler).ChangeName("my-page4")
|
||||
|
||||
// same with Handle/Func
|
||||
app.HandleFunc("GET", "/mypath5/:param1/statichere/:param2/:otherparam/anything/*something", writePathHandler).ChangeName("my-page5")
|
||||
|
||||
app.Get("/mypath6/:param1/:param2/staticParam/:param3AfterStatic", writePathHandler).ChangeName("my-page6")
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
// for /mypath6...
|
||||
paramsAsArray := []string{"param1", "theParam1",
|
||||
"param2", "theParam2",
|
||||
"param3AfterStatic", "theParam3"}
|
||||
|
||||
if err := ctx.Render("page.html", iris.Map{"ParamsAsArray": paramsAsArray}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
})
|
||||
|
||||
app.Get("/redirect/:namedRoute", func(ctx *iris.Context) {
|
||||
routeName := ctx.Param("namedRoute")
|
||||
|
||||
println("The full uri of " + routeName + "is: " + app.URL(routeName))
|
||||
// if routeName == "my-page1"
|
||||
// prints: The full uri of my-page1 is: http://127.0.0.1:8080/mypath
|
||||
ctx.RedirectTo(routeName)
|
||||
// http://127.0.0.1:8080/redirect/my-page1 will redirect to -> http://127.0.0.1:8080/mypath
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
// for gorillamux adaptor is the same thing, the path syntax is the only thing changed ofc.
|
||||
// Note: Here, we could use app.RouteParam("param1") without even care what router is being used,
|
||||
// but I have two examples of the same thing in order to be more understable for you.
|
||||
func startWithGorillamux(app *iris.Framework) {
|
||||
app.Adapt(gorillamux.New())
|
||||
|
||||
app.Get("/mypath", writePathHandler).ChangeName("my-page1")
|
||||
app.Get("/mypath2/{param1}/{param2}", writePathHandler).ChangeName("my-page2")
|
||||
app.Get("/mypath3/{param1}/statichere/{param2}", writePathHandler).ChangeName("my-page3")
|
||||
app.Get("/mypath4/{param1}/statichere/{param2}/{otherparam}/{something:.*}", writePathHandler).ChangeName("my-page4")
|
||||
|
||||
// same with Handle/Func
|
||||
app.HandleFunc("GET", "/mypath5/{param1}/statichere/{param2}/{otherparam}/anything/{something:.*}", writePathHandler).ChangeName("my-page5")
|
||||
|
||||
app.Get("/mypath6/{param1}/{param2}/staticParam/{param3AfterStatic}", writePathHandler).ChangeName("my-page6")
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
// for /mypath6...
|
||||
paramsAsArray := []string{"param1", "theParam1",
|
||||
"param2", "theParam2",
|
||||
"param3AfterStatic", "theParam3"}
|
||||
|
||||
if err := ctx.Render("page.html", iris.Map{"ParamsAsArray": paramsAsArray}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
})
|
||||
|
||||
app.Get("/redirect/{namedRoute}", func(ctx *iris.Context) {
|
||||
routeName := ctx.Param("namedRoute")
|
||||
|
||||
println("The full uri of " + routeName + "is: " + app.URL(routeName))
|
||||
// if routeName == "my-page1"
|
||||
// prints: The full uri of my-page1 is: http://127.0.0.1:8080/mypath
|
||||
ctx.RedirectTo(routeName)
|
||||
// http://127.0.0.1:8080/redirect/my-page1 will redirect to -> http://127.0.0.1:8080/mypath
|
||||
})
|
||||
|
||||
app.Listen("localhost:8080")
|
||||
}
|
||||
|
||||
@@ -1,29 +1,25 @@
|
||||
<a href="{{url "my-page1"}}">http://127.0.0.1:8080/mypath</a>
|
||||
<a href="{{urlpath "my-page1"}}">/mypath</a>
|
||||
<br />
|
||||
<br />
|
||||
|
||||
<a href="{{url "my-page2" "param1" "theParam1" "param2" "theParam2"}}">http://localhost:8080/mypath2/:param1/:param2</a>
|
||||
or path only:
|
||||
<a href="{{urlpath "my-page2" "param1" "theParam1" "param2" "theParam2"}}">/mypath2/:param1/:param2</a>
|
||||
|
||||
<a href="{{urlpath "my-page2" "theParam1" "theParam2"}}">/mypath2/{paramfirst}/{paramsecond}</a>
|
||||
<br />
|
||||
<br />
|
||||
|
||||
<a href="{{url "my-page3" "param1" "theParam1" "param2" "theParam2AfterStatic"}}">
|
||||
http://localhost:8080/mypath3/:param1/statichere/:param2</a>
|
||||
|
||||
<a href="{{urlpath "my-page3" "theParam1" "theParam2AfterStatic"}}">/mypath3/{paramfirst}/statichere/{paramsecond}</a>
|
||||
<br />
|
||||
<br />
|
||||
|
||||
<a href="{{url "my-page4" "param1" "theParam1" "param2" "theparam2AfterStatic" "otherparam" "otherParam" "something" "matchAnything"}}">http://localhost/mypath4/:param1/statichere/:param2/:otherparam/*something</a>
|
||||
|
||||
<a href="{{urlpath "my-page4" "theParam1" "theparam2AfterStatic" "otherParam" "matchAnything"}}">
|
||||
/mypath4/{paramfirst}/statichere/{paramsecond}/{otherparam}/{something:path}</a>
|
||||
<br />
|
||||
<br />
|
||||
|
||||
<a href="{{url "my-page5" "param1" "theParam1" "param2" "theParam2AfterStatic" "otherparam" "otherParam" "something" "matchAnythingAfterStatic"}}">
|
||||
http://localhost:8080/mypath5/:param1/statichere/:param2/:otherparam/anything/*anything</a>
|
||||
|
||||
<a href="{{urlpath "my-page5" "theParam1" "theParam2Afterstatichere" "otherParam" "matchAnythingAfterStatic"}}">
|
||||
/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{anything:path}</a>
|
||||
<br />
|
||||
<br />
|
||||
|
||||
<a href={{url "my-page6" .ParamsAsArray }}>http://localhost:8080/mypath6/{param1}/{param2}/staticParam/{param3AfterStatic}</a>
|
||||
<a href={{urlpath "my-page6" .ParamsAsArray }}>
|
||||
/mypath6/{paramfirst}/{paramsecond}/statichere/{paramThirdAfterStatic}
|
||||
</a>
|
||||
|
||||
@@ -2,52 +2,74 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/gorillamux"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/router"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
const (
|
||||
host = "127.0.0.1:8080"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(gorillamux.New())
|
||||
|
||||
app.Adapt(view.HTML("./templates", ".html"))
|
||||
// create a custom path reverser, iris let you define your own host and scheme
|
||||
// which is useful when you have nginx or caddy in front of iris.
|
||||
rv := router.NewRoutePathReverser(app, router.WithHost(host), router.WithScheme("http"))
|
||||
// locate and define our templates as usual.
|
||||
templates := view.HTML("./templates", ".html")
|
||||
// add a custom func of "url" and pass the rv.URL as its template function body,
|
||||
// so {{url "routename" "paramsOrSubdomainAsFirstArgument"}} will work inside our templates.
|
||||
templates.AddFunc("url", rv.URL)
|
||||
|
||||
app.Get("/mypath", emptyHandler).ChangeName("my-page1")
|
||||
app.Get("/mypath2/{param1}/{param2}", emptyHandler).ChangeName("my-page2")
|
||||
app.Get("/mypath3/{param1}/statichere/{param2}", emptyHandler).ChangeName("my-page3")
|
||||
app.Get("/mypath4/{param1}/statichere/{param2}/{otherparam}/{something:.*}", emptyHandler).ChangeName("my-page4")
|
||||
app.AttachView(templates)
|
||||
|
||||
// same with Handle/Func
|
||||
app.HandleFunc("GET", "/mypath5/{param1}/statichere/{param2}/{otherparam}/anything/{something:.*}", emptyHandler).ChangeName("my-page5")
|
||||
// wildcard subdomain, will catch username1.... username2.... username3... username4.... username5...
|
||||
// that our below links are providing via page.html's first argument which is the subdomain.
|
||||
|
||||
app.Get("/mypath6/{param1}/{param2}/staticParam/{param3AfterStatic}", emptyHandler).ChangeName("my-page6")
|
||||
subdomain := app.Party("*.")
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
// for /mypath6...
|
||||
paramsAsArray := []string{"param1", "theParam1",
|
||||
"param2", "theParam2",
|
||||
"param3AfterStatic", "theParam3"}
|
||||
mypathRoute, _ := subdomain.Get("/mypath", emptyHandler)
|
||||
mypathRoute.Name = "my-page1"
|
||||
|
||||
if err := ctx.Render("page.html", iris.Map{"ParamsAsArray": paramsAsArray}); err != nil {
|
||||
mypath2Route, _ := subdomain.Get("/mypath2/{paramfirst}/{paramsecond}", emptyHandler)
|
||||
mypath2Route.Name = "my-page2"
|
||||
|
||||
mypath3Route, _ := subdomain.Get("/mypath3/{paramfirst}/statichere/{paramsecond}", emptyHandler)
|
||||
mypath3Route.Name = "my-page3"
|
||||
|
||||
mypath4Route, _ := subdomain.Get("/mypath4/{paramfirst}/statichere/{paramsecond}/{otherparam}/{something:path}", emptyHandler)
|
||||
mypath4Route.Name = "my-page4"
|
||||
|
||||
mypath5Route, _ := subdomain.Handle("GET", "/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{something:path}", emptyHandler)
|
||||
mypath5Route.Name = "my-page5"
|
||||
|
||||
mypath6Route, err := subdomain.Get("/mypath6/{paramfirst}/{paramsecond}/staticParam/{paramThirdAfterStatic}", emptyHandler)
|
||||
if err != nil { // catch any route problems when declare a route or on err := app.Run(...); err != nil { panic(err) }
|
||||
panic(err)
|
||||
}
|
||||
mypath6Route.Name = "my-page6"
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
// for username5./mypath6...
|
||||
paramsAsArray := []string{"username5", "theParam1", "theParam2", "paramThirdAfterStatic"}
|
||||
ctx.ViewData("ParamsAsArray", paramsAsArray)
|
||||
if err := ctx.View("page.html"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
})
|
||||
|
||||
app.Get("/redirect/{namedRoute}", func(ctx *iris.Context) {
|
||||
routeName := ctx.Param("namedRoute")
|
||||
|
||||
println("The full uri of " + routeName + "is: " + app.URL(routeName))
|
||||
// if routeName == "my-page1"
|
||||
// prints: The full uri of my-page1 is: http://127.0.0.1:8080/mypath
|
||||
ctx.RedirectTo(routeName)
|
||||
// http://127.0.0.1:8080/redirect/my-page1 will redirect to -> http://127.0.0.1:8080/mypath
|
||||
})
|
||||
|
||||
app.Listen("localhost:8080")
|
||||
// http://127.0.0.1:8080
|
||||
app.Run(iris.Addr(host))
|
||||
}
|
||||
|
||||
func emptyHandler(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from %s.", ctx.Path())
|
||||
func emptyHandler(ctx context.Context) {
|
||||
ctx.Writef("Hello from subdomain: %s , you're in path: %s", ctx.Subdomain(), ctx.Path())
|
||||
}
|
||||
|
||||
// Note:
|
||||
// If you got an empty string on {{ url }} or {{ urlpath }} it means that
|
||||
// args length are not aligned with the route's parameters length
|
||||
// or the route didn't found by the passed name.
|
||||
|
||||
@@ -1,16 +1,29 @@
|
||||
<!-- the only difference between normal named routes and dynamic subdomains named routes is that the first argument of url
|
||||
is the subdomain part instead of named parameter-->
|
||||
|
||||
<a href="{{url "dynamic-subdomain1" "username1"}}">username1.127.0.0.1:8080/mypath</a>
|
||||
<a href="{{url "my-page1" "username1"}}">username1.127.0.0.1:8080/mypath</a>
|
||||
<br />
|
||||
<br />
|
||||
<a href="{{url "dynamic-subdomain2" "username2" "theParam1" "theParam2"}}">username2.127.0.0.1:8080/mypath2/{param1}/{param2}</a>
|
||||
<a href="{{url "my-page2" "username2" "theParam1" "theParam2"}}">
|
||||
username2.127.0.0.1:8080/mypath2/{paramfirst}/{paramsecond}
|
||||
</a>
|
||||
<br />
|
||||
<br />
|
||||
<a href="{{url "dynamic-subdomain3" "username3" "theParam1" "theParam2AfterStatic"}}">username3.127.0.0.1:8080/mypath3/{param1}/statichere/{param2}</a>
|
||||
<a href="{{url "my-page3" "username3" "theParam1" "theParam2AfterStatic"}}">
|
||||
username3.127.0.0.1:8080/mypath3/{paramfirst}/statichere/{paramsecond}
|
||||
</a>
|
||||
<br />
|
||||
<br />
|
||||
<a href="{{url "dynamic-subdomain4" "username4" "theParam1" "theparam2AfterStatic" "otherParam" "matchAnything"}}">username4.127.0.0.1:8080/mypath4/{param1}/statichere/{param2}/{otherParam}/{something:.*}</a>
|
||||
<a href="{{url "my-page4" "username4" "theParam1" "theparam2AfterStatic" "otherParam" "matchAnything"}}">
|
||||
username4.127.0.0.1:8080/mypath4/{paramfirst}/statichere/{paramsecond}/{otherParam}/{something:path}
|
||||
</a>
|
||||
<br />
|
||||
<br />
|
||||
<a href="{{url "dynamic-subdomain5" .ParamsAsArray }}" >username5.127.0.0.1:8080/mypath6/{param1}/{param2}/staticParam/{param3}AfterStatic</a>
|
||||
<a href="{{url "my-page5" "username5" "theParam1" "theparam2AfterStatic" "otherParam" "matchAnything"}}">
|
||||
username5.127.0.0.1:8080/mypath5/{paramfirst}/statichere/{paramsecond}/{otherparam}/anything/{something:path}
|
||||
</a>
|
||||
<br/>
|
||||
<br/>
|
||||
<a href="{{url "my-page6" .ParamsAsArray }}">
|
||||
username5.127.0.0.1:8080/mypath6/{paramfirst}/{paramsecond}/staticParam/{paramThirdAfterStatic}
|
||||
</a>
|
||||
|
||||
@@ -5,10 +5,11 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/websocket"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/view"
|
||||
"github.com/kataras/iris/websocket"
|
||||
)
|
||||
|
||||
type clientPage struct {
|
||||
@@ -18,12 +19,11 @@ type clientPage struct {
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
app.Adapt(view.HTML("./templates", ".html")) // select the html engine to serve templates
|
||||
app.AttachView(view.HTML("./templates", ".html")) // select the html engine to serve templates
|
||||
|
||||
ws := websocket.New(websocket.Config{
|
||||
// the path which the websocket client should listen/registered to,
|
||||
// the request path which the websocket client should listen/registered to the server,
|
||||
// the endpoint is like a route.
|
||||
Endpoint: "/my_endpoint",
|
||||
// the client-side javascript static file path
|
||||
// which will be served by Iris.
|
||||
@@ -44,15 +44,16 @@ func main() {
|
||||
// an ID for each incoming websocket connections (clients).
|
||||
// The request is an argument which you can use to generate the ID (from headers for example).
|
||||
// If empty then the ID is generated by DefaultIDGenerator: randomString(64):
|
||||
// IDGenerator func(ctx *iris.Context) string {},
|
||||
// IDGenerator func(ctx context.Context) string {},
|
||||
})
|
||||
|
||||
app.Adapt(ws) // adapt the websocket server, you can adapt more than one with different Endpoint
|
||||
ws.Attach(app) // adapt the application to the websocket server
|
||||
|
||||
app.StaticWeb("/js", "./static/js") // serve our custom javascript code
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Render("client.html", clientPage{"Client Page", ctx.ServerHost()})
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.ViewData("", clientPage{"Client Page", "localhost:8080"})
|
||||
ctx.View("client.html")
|
||||
})
|
||||
|
||||
Conn := make(map[websocket.Connection]bool)
|
||||
@@ -103,7 +104,7 @@ func main() {
|
||||
}
|
||||
}()
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func broadcast(Conn map[websocket.Connection]bool, message string) {
|
||||
|
||||
@@ -2,19 +2,17 @@ package main
|
||||
|
||||
// Run first `go run main.go server`
|
||||
// and `go run main.go client` as many times as you want.
|
||||
// Originally written by: github.com/antlaw to describe an old kataras/go-websocket's issue
|
||||
// which you can find here: https://github.com/kataras/go-websocket/issues/24
|
||||
// Originally written by: github.com/antlaw to describe an old issue.
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/websocket"
|
||||
|
||||
xwebsocket "golang.org/x/net/websocket"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/websocket"
|
||||
)
|
||||
|
||||
// WS is the current websocket connection
|
||||
@@ -65,7 +63,7 @@ func recvUntilErr() {
|
||||
//ConnectWebSocket connect a websocket to host
|
||||
func ConnectWebSocket() error {
|
||||
var origin = "http://localhost/"
|
||||
var url = "ws://localhost:9090/socket"
|
||||
var url = "ws://localhost:8080/socket"
|
||||
var err error
|
||||
WS, err = xwebsocket.Dial(url, "", origin)
|
||||
return err
|
||||
@@ -136,14 +134,14 @@ func OnConnect(c websocket.Connection) {
|
||||
// ServerLoop listen and serve websocket requests
|
||||
func ServerLoop() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
// enable all (error) logs
|
||||
// select the httprouter as the servemux
|
||||
|
||||
ws := websocket.New(websocket.Config{Endpoint: "/socket"})
|
||||
app.Adapt(ws)
|
||||
ws.Attach(app)
|
||||
|
||||
ws.OnConnection(OnConnect)
|
||||
app.Listen("0.0.0.0:9090")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -3,10 +3,11 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/websocket"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/view"
|
||||
"github.com/kataras/iris/websocket"
|
||||
)
|
||||
|
||||
/* Native messages no need to import the iris-ws.js to the ./templates.client.html
|
||||
@@ -24,9 +25,9 @@ type clientPage struct {
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
app.Adapt(view.HTML("./templates", ".html")) // select the html engine to serve templates
|
||||
// enable all (error) logs
|
||||
// select the httprouter as the servemux
|
||||
app.AttachView(view.HTML("./templates", ".html")) // select the html engine to serve templates
|
||||
|
||||
ws := websocket.New(websocket.Config{
|
||||
// the path which the websocket client should listen/registered to,
|
||||
@@ -35,12 +36,13 @@ func main() {
|
||||
// BinaryMessages: true,
|
||||
})
|
||||
|
||||
app.Adapt(ws) // adapt the websocket server, you can adapt more than one with different Endpoint
|
||||
ws.Attach(app) // adapt the websocket server, you can adapt more than one with different Endpoint
|
||||
|
||||
app.StaticWeb("/js", "./static/js") // serve our custom javascript code
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Render("client.html", clientPage{"Client Page", ctx.Host()})
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.ViewData("", clientPage{"Client Page", "localhost:8080"})
|
||||
ctx.View("client.html")
|
||||
})
|
||||
|
||||
ws.OnConnection(func(c websocket.Connection) {
|
||||
@@ -57,6 +59,6 @@ func main() {
|
||||
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
|
||||
}
|
||||
|
||||
@@ -3,10 +3,11 @@ package main
|
||||
import (
|
||||
"fmt" // optional
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/websocket"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/view"
|
||||
"github.com/kataras/iris/websocket"
|
||||
)
|
||||
|
||||
type clientPage struct {
|
||||
@@ -16,12 +17,11 @@ type clientPage struct {
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
app.Adapt(view.HTML("./templates", ".html")) // select the html engine to serve templates
|
||||
app.AttachView(view.HTML("./templates", ".html")) // select the html engine to serve templates
|
||||
|
||||
ws := websocket.New(websocket.Config{
|
||||
// the path which the websocket client should listen/registered to,
|
||||
// the request path which the websocket client should listen/registered to the server,
|
||||
// the endpoint is like a route.
|
||||
Endpoint: "/my_endpoint",
|
||||
// the client-side javascript static file path
|
||||
// which will be served by Iris.
|
||||
@@ -42,21 +42,22 @@ func main() {
|
||||
// an ID for each incoming websocket connections (clients).
|
||||
// The request is an argument which you can use to generate the ID (from headers for example).
|
||||
// If empty then the ID is generated by DefaultIDGenerator: randomString(64):
|
||||
// IDGenerator func(ctx *iris.Context) string {},
|
||||
// IDGenerator func(ctx context.Context) string {},
|
||||
})
|
||||
|
||||
app.Adapt(ws) // adapt the websocket server, you can adapt more than one with different Endpoint
|
||||
ws.Attach(app) // adapt the websocket server, you can adapt more than one with different Endpoint
|
||||
|
||||
app.StaticWeb("/js", "./static/js") // serve our custom javascript code
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Render("client.html", clientPage{"Client Page", ctx.Host()})
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.ViewData("", clientPage{"Client Page", ctx.Host()})
|
||||
ctx.View("client.html")
|
||||
})
|
||||
|
||||
var myChatRoom = "room1"
|
||||
|
||||
ws.OnConnection(func(c websocket.Connection) {
|
||||
// Context returns the (upgraded) *iris.Context of this connection
|
||||
// Context returns the (upgraded) context.Context of this connection
|
||||
// avoid using it, you normally don't need it,
|
||||
// websocket has everything you need to authenticate the user BUT if it's necessary
|
||||
// then you use it to receive user information, for example: from headers.
|
||||
@@ -95,5 +96,5 @@ func main() {
|
||||
})
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -3,9 +3,10 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/websocket"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/websocket"
|
||||
)
|
||||
|
||||
func handleConnection(c websocket.Connection) {
|
||||
@@ -16,16 +17,16 @@ func handleConnection(c websocket.Connection) {
|
||||
// Print the message to the console
|
||||
fmt.Printf("%s sent: %s\n", c.Context().RemoteAddr(), msg)
|
||||
|
||||
// Write message back to browser
|
||||
c.Emit("chat", msg)
|
||||
// Write message back to the client message owner:
|
||||
// c.Emit("chat", msg)
|
||||
|
||||
c.To(websocket.Broadcast).Emit("chat", msg)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
// create our echo websocket server
|
||||
ws := websocket.New(websocket.Config{
|
||||
@@ -36,13 +37,16 @@ func main() {
|
||||
|
||||
ws.OnConnection(handleConnection)
|
||||
|
||||
// Adapt the websocket server.
|
||||
// you can adapt more than one of course.
|
||||
app.Adapt(ws)
|
||||
// Adapt the application to the websocket server.
|
||||
ws.Attach(app)
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.ServeFile("websockets.html", false) // second parameter: enable gzip?
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
// x2
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080
|
||||
// write something, press submit, see the result.
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -18,12 +18,16 @@
|
||||
|
||||
// read events from the server
|
||||
socket.On("chat", function (msg) {
|
||||
output.innerHTML += "Server: " + msg + "\n";
|
||||
addMessage(msg)
|
||||
});
|
||||
|
||||
function send() {
|
||||
// send chat event data to the server
|
||||
socket.Emit("chat", input.value);
|
||||
input.value = "";
|
||||
addMessage("Me: "+input.value) // write ourselves
|
||||
socket.Emit("chat", input.value);// send chat event data to the websocket server
|
||||
input.value = ""; // clear the input
|
||||
}
|
||||
|
||||
function addMessage(msg) {
|
||||
output.innerHTML += msg + "\n";
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -6,10 +6,11 @@ import (
|
||||
"os" // optional
|
||||
"time" // optional
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/websocket"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/view"
|
||||
"github.com/kataras/iris/websocket"
|
||||
)
|
||||
|
||||
type clientPage struct {
|
||||
@@ -19,53 +20,31 @@ type clientPage struct {
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
app.Adapt(view.HTML("./templates", ".html")) // select the html engine to serve templates
|
||||
app.AttachView(view.HTML("./templates", ".html")) // select the html engine to serve templates
|
||||
|
||||
ws := websocket.New(websocket.Config{
|
||||
// the path which the websocket client should listen/registered to,
|
||||
Endpoint: "/my_endpoint",
|
||||
// the client-side javascript static file path
|
||||
// which will be served by Iris.
|
||||
// default is /iris-ws.js
|
||||
// if you change that you have to change the bottom of templates/client.html
|
||||
// script tag:
|
||||
Endpoint: "/my_endpoint",
|
||||
ClientSourcePath: "/iris-ws.js",
|
||||
//
|
||||
// Set the timeouts, 0 means no timeout
|
||||
// websocket has more configuration, go to ../../config.go for more:
|
||||
// WriteTimeout: 0,
|
||||
// ReadTimeout: 0,
|
||||
// by-default all origins are accepted, you can change this behavior by setting:
|
||||
// CheckOrigin: (r *http.Request ) bool {},
|
||||
//
|
||||
//
|
||||
// IDGenerator used to create (and later on, set)
|
||||
// an ID for each incoming websocket connections (clients).
|
||||
// The request is an argument which you can use to generate the ID (from headers for example).
|
||||
// If empty then the ID is generated by DefaultIDGenerator: randomString(64):
|
||||
// IDGenerator func(ctx *iris.Context) string {},
|
||||
})
|
||||
|
||||
app.Adapt(ws) // adapt the websocket server, you can adapt more than one with different Endpoint
|
||||
ws.Attach(app)
|
||||
|
||||
app.StaticWeb("/js", "./static/js") // static route to serve our javascript files
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.StaticWeb("/js", "./static/js")
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
// send our custom javascript source file before client really asks for that
|
||||
// using the new go v1.8's HTTP/2 Push.
|
||||
// using the go v1.8's HTTP/2 Push.
|
||||
// Note that you have to listen using ListenTLS in order this to work.
|
||||
if err := ctx.Push("/js/chat.js", nil); err != nil {
|
||||
app.Log(iris.DevMode, err.Error())
|
||||
if err := ctx.ResponseWriter().Push("/js/chat.js", nil); err != nil {
|
||||
ctx.Application().Log(err.Error())
|
||||
}
|
||||
ctx.Render("client.html", clientPage{"Client Page", ctx.Host()})
|
||||
ctx.ViewData("", clientPage{"Client Page", ctx.Host()})
|
||||
ctx.View("client.html")
|
||||
})
|
||||
|
||||
var myChatRoom = "room1"
|
||||
|
||||
ws.OnConnection(func(c websocket.Connection) {
|
||||
// Context returns the (upgraded) *iris.Context of this connection
|
||||
// Context returns the (upgraded) context.Context of this connection
|
||||
// avoid using it, you normally don't need it,
|
||||
// websocket has everything you need to authenticate the user BUT if it's necessary
|
||||
// then you use it to receive user information, for example: from headers.
|
||||
@@ -109,7 +88,7 @@ func main() {
|
||||
}
|
||||
|
||||
// a test listenTLS for our localhost
|
||||
func listenTLS(app *iris.Framework) {
|
||||
func listenTLS(app *iris.Application) {
|
||||
|
||||
const (
|
||||
testTLSCert = `-----BEGIN CERTIFICATE-----
|
||||
@@ -179,19 +158,14 @@ QG+tmveBBIYMed5YbWstZu/95lIHF+u8Hl+Z6xgveozfE5yqiUA=
|
||||
certFile.WriteString(testTLSCert)
|
||||
keyFile.WriteString(testTLSKey)
|
||||
|
||||
// add an event when control+C pressed, to remove the temp cert and key files.
|
||||
app.Adapt(iris.EventPolicy{
|
||||
Interrupted: func(*iris.Framework) {
|
||||
certFile.Close()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
os.Remove(certFile.Name())
|
||||
|
||||
keyFile.Close()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
os.Remove(keyFile.Name())
|
||||
},
|
||||
})
|
||||
|
||||
// https://localhost
|
||||
app.ListenTLS("localhost:443", certFile.Name(), keyFile.Name())
|
||||
|
||||
certFile.Close()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
os.Remove(certFile.Name())
|
||||
|
||||
keyFile.Close()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
os.Remove(keyFile.Name())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user