Add More Examples & Categorized in Folders & TOC

Former-commit-id: ce4d711a75a4ba08ffab075e6baa88724725885b
This commit is contained in:
Gerasimos (Makis) Maropoulos 2017-03-24 00:22:05 +02:00
parent 64ecc88195
commit 55c250c93a
97 changed files with 338 additions and 193 deletions

View File

@ -90,7 +90,7 @@ Feature Overview
- Automatically install and serve certificates from https://letsencrypt.org
- Robust routing and middleware ecosystem
- Build RESTful APIs
- Choose your favorite routes' path syntax between [httprouter](https://github.com/kataras/iris/blob/v6/adaptors/httprouter/_example/main.go) and [gorillamux](https://github.com/kataras/iris/blob/v6/adaptors/gorillamux/_example/main.go)
- Choose your favorite routes' path syntax between [httprouter](https://github.com/kataras/iris/blob/v6/_examples/beginner/routes-using-httprouter/main.go) and [gorillamux](https://github.com/kataras/iris/blob/v6/_examples/beginner/routes-using-gorillamux/main.go)
- Request-Scoped Transactions
- Group API's and subdomains with wildcard support
- Body binding for JSON, XML, Forms, can be extended to use your own custom binders
@ -275,12 +275,9 @@ FAQ & Documentation
4. [Creating A URL Shortener Service Using Go, Iris, and Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
5. [./adaptors](https://github.com/kataras/iris/tree/v6/adaptors) and [./middleware](https://github.com/kataras/iris/tree/v6/middleware) contains examples of their usage
5. [Godocs](https://godoc.org/gopkg.in/kataras/iris.v6) for deep documentation
6. [Godocs](https://godoc.org/gopkg.in/kataras/iris.v6) for deep documentation
7. [HISTORY.md](https://github.com//kataras/iris/tree/v6/HISTORY.md) is your best friend, version migrations are released there
6. [HISTORY.md](https://github.com//kataras/iris/tree/v6/HISTORY.md) is your best friend, version migrations are released there
I'll be glad to talk with you about **your awesome feature requests**,
@ -480,14 +477,14 @@ i.e:
- [transaction_test.go](https://github.com/kataras/iris/blob/v6/transaction_test.go)
- [serializer_test.go](https://github.com/kataras/iris/blob/v6/serializer_test.go)
A simple test is located to [./httptest/_example/main_test.go](https://github.com/kataras/iris/blob/v6/httptest/_example/main_test.go)
A simple test is located to [./_examples/advanced/httptest/main_test.go](https://github.com/kataras/iris/blob/v6/_examples/advanced/httptest/main_test.go)
Philosophy
------------
The Iris philosophy is to provide robust tooling for HTTP, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs. Keep note that, today, iris is faster than nginx itself.
Iris does not force you to use any specific ORM or template engine. Iris is routerless which means you can adapt any router you like, [httprouter](https://github.com/kataras/iris/blob/v6/adaptors/httprouter/_example/main.go) is the fastest, [gorillamux](https://github.com/kataras/iris/blob/v6/adaptors/gorillamux/_example/main.go) has more features. With support for the most used template engines (5), you can quickly craft the perfect application.
Iris does not force you to use any specific ORM or template engine. Iris is routerless which means you can adapt any router you like, [httprouter](https://github.com/kataras/iris/blob/v6/_examples/beginner/routes-using-httprouter/main.go) is the fastest, [gorillamux](https://github.com/kataras/iris/blob/v6/_examples/beginner/routes-using-gorillamux/main.go) has more features. With support for the most used template engines (5), you can quickly craft the perfect application.
People

View File

@ -1,4 +1,4 @@
## Examples
# Examples
This folder provides easy to understand code snippets on how to get started with web development with the Go programming language using the [Iris](https://github.com/kataras/iris) web framework.
@ -8,26 +8,60 @@ It doesn't contains "best ways" neither explains all its features. It's just a s
Developers should read the official [documentation](https://godoc.org/gopkg.in/kataras/iris.v6) in depth.
<a href ="https://github.com/kataras/iris"> <img src="http://iris-go.com/assets/book/cover_4.jpg" width="300" /> </a>
<a href ="https://github.com/kataras/iris"> <img align="right" src="http://iris-go.com/assets/book/cover_4.jpg" width="300" /> </a>
## Table of Contents
* [Hello World](examples/hello-world/main.go)
* [Routes (using httprouter)](examples/routes-using-httprouter/main.go)
* [Routes (using gorillamux)](examples/routes-using-gorillamux/main.go)
* [Templates](examples/templates/main.go)
* [Forms](examples/forms/main.go)
* [JSON](examples/json/main.go)
* [Upload Files](examples/upload-files/main.go)
* [Static Files](examples/static-files/main.go)
* [Favicon](examples/favicon/main.go)
* [Password Hashing](examples/password-hashing/main.go)
* [Sessions](examples/sessions/main.go)
* [Websockets](examples/websockets/main.go)
* [Markdown and Cache](examples/cache-markdown/main.go)
* [Online Visitors](examples/online-visitors/main.go)
* [URL Shortener using BoltDB](examples/url-shortener/main.go)
* [Level: Beginner](examples/beginner)
* [Hello World](examples/beginner/hello-world/main.go)
* [Routes (using httprouter)](examples/beginner/routes-using-httprouter/main.go)
* [Routes (using gorillamux)](examples/beginner/routes-using-gorillamux/main.go)
* [Write JSON](examples/beginner/write-json/main.go)
* [Read JSON](examples/beginner/read-json/main.go)
* [Read Form](examples/beginner/read-form/main.go)
* [Favicon](examples/beginner/favicon/main.go)
* [File Server](examples/beginner/file-server/main.go)
* [Send Files](examples/beginner/send-files/main.go)
* [Level: Intermediate](examples/intermediate)
* [Send An E-mail](examples/intermediate/e-mail/main.go)
* [Upload/Read Files](examples/intermediate/upload-files/main.go)
* [Request Logger](examples/intermediate/request-logger/main.go)
* [Profiling (pprof)](examples/intermediate/pprof/main.go)
* [Basic Authentication](examples/intermediate/basicauth/main.go)
* [HTTP Access Control](examples/intermediate/cors/main.go)
* [Cache Markdown](examples/intermediate/cache-markdown/main.go)
* [Localization and Internationalization](examples/intermediate/i18n/main.go)
* [Recovery](examples/intermediate/recover/main.go)
* [Graceful Shutdown](examples/intermediate/graceful-shutdown/main.go)
* [View Engine](examples/intermediate/view)
* [Overview](examples/intermediate/view/overview/main.go)
* [Embedding Templates Into Executable](examples/intermediate/embedding-templates-into-app)
* [Template HTML: Part Zero](examples/intermediate/view/template_html_0/main.go)
* [Template HTML: Part One](examples/intermediate/view/template_html_1/main.go)
* [Template HTML: Part Two](examples/intermediate/view/template_html_2/main.go)
* [Template HTML: Part Three](examples/intermediate/view/template_html_3/main.go)
* [Template HTML: Part Four](examples/intermediate/view/template_html_4/main.go)
* [Custom Renderer](examples/intermediate/view/custom-renderer/main.go)
* [Password Hashing](examples/intermediate/password-hashing/main.go)
* [Sessions](examples/intermediate/sessions)
* [Overview](examples/intermediate/sessions/overview/main.go)
* [Encoding & Decoding the Session ID: Secure Cookie](examples/intermediate/sessions/securecookie/main.go)
* [Standalone](examples/intermediate/sessions/standalone/main.go)
* [With A Back-End Database](examples/intermediate/sessions/database/main.go)
* [Flash Messages](examples/intermediate/flash-messages/main.go)
* [Websockets](examples/intermediate/websockets)
* [Ridiculous Simple](examples/intermediate/websockets/ridiculous-simple/main.go)
* [Overview](examples/intermediate/websockets/overview/main.go)
* [Connection List](examples/intermediate/websockets/connectionlist/main.go)
* [Native Messages](examples/intermediate/websockets/naive-messages/main.go)
* [Secure](examples/intermediate/websockets/secure/main.go)
* [Custom Go Client](examples/intermediate/websockets/custom-go-client/main.go)
* [Level: Advanced](examples/advanced)
* [HTTP Testing](examples/advanced/httptest/main_test.go)
* [Watch & Compile Typescript source files](examples/advanced/typescript/main.go)
* [Cloud Editor](examples/advanced/cloud-editor/main.go)
* [Online Visitors](examples/advanced/online-visitors/main.go)
* [URL Shortener using BoltDB](examples/advanced/url-shortener/main.go)
> Take look at the [community examples](https://github.com/iris-contrib/examples) too!
> Take look at the [community examples](https://github.com/iris-contrib/examples) too!

View File

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,42 @@
// package main contains an example on how to use the ReadForm, but with the same way you can do the ReadJSON & ReadJSON
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
)
type Visitor struct {
Username string
Mail string
Data []string `form:"mydata"`
}
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 html template engine
app.Adapt(view.HTML("./templates", ".html"))
app.Get("/", func(ctx *iris.Context) {
if err := ctx.Render("form.html", nil); err != nil {
ctx.Log(iris.DevMode, err.Error())
}
})
app.Post("/form_action", func(ctx *iris.Context) {
visitor := Visitor{}
err := ctx.ReadForm(&visitor)
if err != nil {
ctx.Log(iris.DevMode, "Error when reading form: "+err.Error())
}
ctx.Writef("Visitor: %#v", visitor)
})
app.Listen(":8080")
}

View File

@ -0,0 +1,19 @@
<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<body>
<form action="/form_action" method="post">
<input type="text" name="Username" /> <br /> <input type="text"
name="Mail" /><br /> <select multiple="multiple" name="mydata">
<option value='one'>One</option>
<option value='two'>Two</option>
<option value='three'>Three</option>
<option value='four'>Four</option>
</select>
<hr />
<input type="submit" value="Send data" />
</form>
</body>
</html>

View File

@ -0,0 +1,36 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
)
type Company struct {
Name string
City string
Other string
}
func MyHandler(ctx *iris.Context) {
c := &Company{}
if err := ctx.ReadJSON(c); err != nil {
ctx.Log(iris.DevMode, err.Error())
return
}
ctx.Writef("Company: %#v\n", c)
}
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())
// use postman or whatever to do a POST request
// to the http://localhost:8080 with BODY: JSON PAYLOAD
// and Content-Type to application/json
app.Post("/", MyHandler)
app.Listen(":8080")
}

Binary file not shown.

View File

@ -0,0 +1,21 @@
package main
import (
"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("/servezip", func(c *iris.Context) {
file := "./files/first.zip"
c.SendFile(file, "c.zip")
})
app.Listen(":8080")
}

View File

@ -1,47 +0,0 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
)
// ContactDetails the information from user
type ContactDetails struct {
Email string `form:"email"`
Subject string `form:"subject"`
Message string `form:"message"`
}
func main() {
app := iris.New()
app.Adapt(httprouter.New())
// Parse all files inside `./mytemplates` directory ending with `.html`
app.Adapt(view.HTML("./mytemplates", ".html"))
app.Get("/", func(ctx *iris.Context) {
ctx.Render("forms.html", nil)
})
// Equivalent with app.HandleFunc("POST", ...)
app.Post("/", func(ctx *iris.Context) {
// details := ContactDetails{
// Email: ctx.FormValue("email"),
// Subject: ctx.FormValue("subject"),
// Message: ctx.FormValue("message"),
// }
// or simply:
var details ContactDetails
ctx.ReadForm(&details)
// do something with details
_ = details
ctx.Render("forms.html", struct{ Success bool }{true})
})
app.Listen(":8080")
}

View File

@ -1,14 +0,0 @@
{{if .Success}}
<h1>Thanks for your message!</h1>
{{else}}
<h1>Contact</h1>
<form method="POST">
<label>Email:</label><br />
<input type="text" name="email"><br />
<label>Subject:</label><br />
<input type="text" name="subject"><br />
<label>Message:</label><br />
<textarea name="message"></textarea><br />
<input type="submit">
</form>
{{end}}

View File

@ -0,0 +1,77 @@
package main
import (
"bytes"
"github.com/kataras/go-mailer"
"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())
// 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")
}

View File

@ -0,0 +1,7 @@
<h1>Hello From Iris web framework</h1>
<br />
<br />
<span style="color: red"> {{.Message}}</span>
<hr />
<b> {{.Footer}} </b>

View File

@ -0,0 +1,45 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/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) {
ctx.Session().SetFlash("name", "iris")
ctx.Writef("Message setted, is available for the next request")
})
app.Get("/get", func(ctx *iris.Context) {
name := ctx.Session().GetFlashString("name")
if name != "" {
ctx.Writef("Empty name!!")
return
}
ctx.Writef("Hello %s", name)
})
app.Get("/test", func(ctx *iris.Context) {
name := ctx.Session().GetFlashString("name")
if name != "" {
ctx.Writef("Empty name!!")
return
}
ctx.Writef("Ok you are comming from /set ,the value of the name is %s", name)
ctx.Writef(", and again from the same context: %s", name)
})
app.Listen(":8080")
}

View File

@ -0,0 +1,32 @@
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")
}

View File

@ -1,28 +0,0 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/gorillamux"
)
func main() {
app := iris.New()
// Adapt the "httprouter", you can use "gorillamux" too.
app.Adapt(gorillamux.New())
userAges := map[string]int{
"Alice": 25,
"Bob": 30,
"Claire": 29,
}
// Equivalent with app.HandleFunc("GET", ...)
app.Get("/users/{name}", func(ctx *iris.Context) {
name := ctx.Param("name")
age := userAges[name]
ctx.Writef("%s is %d years old!", name, age)
})
app.Listen(":8080")
}

View File

@ -1,27 +0,0 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
)
func main() {
app := iris.New()
app.Adapt(httprouter.New())
userAges := map[string]int{
"Alice": 25,
"Bob": 30,
"Claire": 29,
}
// Equivalent with app.HandleFunc("GET", ...)
app.Get("/users/:name", func(ctx *iris.Context) {
name := ctx.Param("name")
age := userAges[name]
ctx.Writef("%s is %d years old!", name, age)
})
app.Listen(":8080")
}

View File

@ -1,39 +0,0 @@
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
"gopkg.in/kataras/iris.v6/adaptors/view"
)
// Todo bind struct
type Todo struct {
Task string
Done bool
}
func main() {
// Configuration is optional
app := iris.New(iris.Configuration{Gzip: false, Charset: "UTF-8"})
// Adapt a logger which will print all errors to os.Stdout
app.Adapt(iris.DevLogger())
// Adapt the httprouter (we will use that on all examples)
app.Adapt(httprouter.New())
// Parse all files inside `./mytemplates` directory ending with `.html`
app.Adapt(view.HTML("./mytemplates", ".html"))
todos := []Todo{
{"Learn Go", true},
{"Read GopherBOOk", true},
{"Create a web app in Go", false},
}
app.Get("/", func(ctx *iris.Context) {
ctx.Render("todos.html", struct{ Todos []Todo }{todos})
})
app.Listen(":8080")
}

View File

@ -1,10 +0,0 @@
<h1>Todos</h1>
<ul>
{{range .Todos}}
{{if .Done}}
<li><s>{{.Task}}</s></li>
{{else}}
<li>{{.Task}}</li>
{{end}}
{{end}}
</ul>

2
doc.go
View File

@ -605,7 +605,7 @@ Example code:
djangoEngine.Binary(asset, assetNames)
app.Adapt(djangoEngine)
A real example can be found here: https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_binary .
A real example can be found here: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/embedding-templates-into-app.
Enable auto-reloading of templates on each request. Useful while developers are in dev mode
as they no neeed to restart their app on every template edit.