mirror of
https://github.com/kataras/iris.git
synced 2026-05-13 17:43:49 +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:
58
_examples/beginner/basicauth/main.go
Normal file
58
_examples/beginner/basicauth/main.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/middleware/basicauth"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
authConfig := basicauth.Config{
|
||||
Users: map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"},
|
||||
Realm: "Authorization Required", // defaults to "Authorization Required"
|
||||
ContextKey: "user", // defaults to "user"
|
||||
Expires: time.Duration(30) * time.Minute,
|
||||
}
|
||||
|
||||
authentication := basicauth.New(authConfig)
|
||||
|
||||
// to global app.Use(authentication) (or app.UseGlobal before the .Run)
|
||||
// to routes
|
||||
/*
|
||||
app.Get("/mysecret", authentication, func(ctx context.Context) {
|
||||
username := ctx.Values().GetString("user") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s ", username)
|
||||
})
|
||||
*/
|
||||
|
||||
app.Get("/", func(ctx context.Context) { ctx.Redirect("/admin") })
|
||||
|
||||
// to party
|
||||
|
||||
needAuth := app.Party("/admin", authentication)
|
||||
{
|
||||
//http://localhost:8080/admin
|
||||
needAuth.Get("/", func(ctx context.Context) {
|
||||
username := ctx.Values().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 context.Context) {
|
||||
username := ctx.Values().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 context.Context) {
|
||||
username := authConfig.User(ctx) // shortcut for ctx.Values().GetString("mycustomkey")
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
}
|
||||
|
||||
// open http://localhost:8080/admin
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
29
_examples/beginner/configuration/basic/main.go
Normal file
29
_examples/beginner/configuration/basic/main.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// [...]
|
||||
|
||||
// Good when you want to modify the whole configuration.
|
||||
app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.Configuration{ // default configuration:
|
||||
DisableBanner: false,
|
||||
DisableTray: false,
|
||||
DisableInterruptHandler: false,
|
||||
DisablePathCorrection: false,
|
||||
EnablePathEscape: false,
|
||||
FireMethodNotAllowed: false,
|
||||
DisableBodyConsumptionOnUnmarshal: false,
|
||||
DisableAutoFireStatusCode: false,
|
||||
TimeFormat: "Mon, 02 Jan 2006 15:04:05 GMT",
|
||||
Charset: "UTF-8",
|
||||
}))
|
||||
|
||||
// or before run:
|
||||
// app.Configure(iris.WithConfiguration(...))
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
DisableTray: true
|
||||
DisablePathCorrection = false
|
||||
EnablePathEscape = false
|
||||
FireMethodNotAllowed = true
|
||||
DisableBodyConsumptionOnUnmarshal = false
|
||||
TimeFormat = "Mon, 01 Jan 2006 15:04:05 GMT"
|
||||
Charset = "UTF-8"
|
||||
|
||||
[Other]
|
||||
MyServerName = "Iris"
|
||||
18
_examples/beginner/configuration/from-toml-file/main.go
Normal file
18
_examples/beginner/configuration/from-toml-file/main.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// [...]
|
||||
|
||||
// Good when you have two configurations, one for development and a different one for production use.
|
||||
app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.TOML("./configs/iris.tml")))
|
||||
|
||||
// or before run:
|
||||
// app.Configure(iris.WithConfiguration(iris.TOML("./configs/iris.tml")))
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
DisableTray: true
|
||||
DisablePathCorrection: false
|
||||
EnablePathEscape: false
|
||||
FireMethodNotAllowed: true
|
||||
DisableBodyConsumptionOnUnmarshal: true
|
||||
TimeFormat: Mon, 01 Jan 2006 15:04:05 GMT
|
||||
Charset: UTF-8
|
||||
18
_examples/beginner/configuration/from-yaml-file/main.go
Normal file
18
_examples/beginner/configuration/from-yaml-file/main.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// [...]
|
||||
|
||||
// Good when you have two configurations, one for development and a different one for production use.
|
||||
app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.YAML("./configs/iris.yml")))
|
||||
|
||||
// or before run:
|
||||
// app.Configure(iris.WithConfiguration(iris.YAML("./configs/iris.yml")))
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
19
_examples/beginner/configuration/functional/main.go
Normal file
19
_examples/beginner/configuration/functional/main.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// [...]
|
||||
|
||||
// Good when you want to change some of the configuration's field.
|
||||
// I use that method :)
|
||||
app.Run(iris.Addr(":8080"), iris.WithoutBanner, iris.WithTray, iris.WithCharset("UTF-8"))
|
||||
|
||||
// or before run:
|
||||
// app.Configure(iris.WithoutBanner, iris.WithTray, iris.WithCharset("UTF-8"))
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
43
_examples/beginner/convert-handlers/negroni-like/main.go
Normal file
43
_examples/beginner/convert-handlers/negroni-like/main.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/handlerconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
irisMiddleware := handlerconv.FromStdWithNext(negronilikeTestMiddleware)
|
||||
app.Use(irisMiddleware)
|
||||
|
||||
// Method GET: http://localhost:8080/
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("<h1> Home </h1>")
|
||||
// this will print an error,
|
||||
// this route's handler will never be executed because the middleware's criteria not passed.
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/ok
|
||||
app.Get("/ok", func(ctx context.Context) {
|
||||
ctx.Writef("Hello world!")
|
||||
// this will print "OK. Hello world!".
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/ok
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func negronilikeTestMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
if r.URL.Path == "/ok" && r.Method == "GET" {
|
||||
w.Write([]byte("OK. "))
|
||||
next(w, r) // go to the next route's handler
|
||||
return
|
||||
}
|
||||
// else print an error and do not forward to the route's handler.
|
||||
w.WriteHeader(iris.StatusBadRequest)
|
||||
w.Write([]byte("Bad request"))
|
||||
}
|
||||
33
_examples/beginner/convert-handlers/nethttp/main.go
Normal file
33
_examples/beginner/convert-handlers/nethttp/main.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/handlerconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
irisMiddleware := handlerconv.FromStd(nativeTestMiddleware)
|
||||
app.Use(irisMiddleware)
|
||||
|
||||
// Method GET: http://localhost:8080/
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("Home")
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/ok
|
||||
app.Get("/ok", func(ctx context.Context) {
|
||||
ctx.HTML("<b>Hello world!</b>")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/ok
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func nativeTestMiddleware(w http.ResponseWriter, r *http.Request) {
|
||||
println("Request path: " + r.URL.Path)
|
||||
}
|
||||
87
_examples/beginner/e-mail/main.go
Normal file
87
_examples/beginner/e-mail/main.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/kataras/go-mailer"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
app := iris.New()
|
||||
app.AttachView(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 context.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("<b> Problem while sending the e-mail: " + err.Error())
|
||||
} else {
|
||||
ctx.HTML("<h1> SUCCESS </h1>")
|
||||
}
|
||||
})
|
||||
|
||||
// send a body by template
|
||||
app.Get("/send/template", func(ctx context.Context) {
|
||||
// we will not use ctx.View
|
||||
// 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.View parameter first.
|
||||
//
|
||||
// the rest of the parameters are the same and the behavior is the same as ctx.View,
|
||||
// except the 'where to render'
|
||||
buff := &bytes.Buffer{}
|
||||
|
||||
// View executes and writes the result of a template file to the writer.
|
||||
//
|
||||
// First parameter is the writer to write the parsed template.
|
||||
// Second parameter is the relative, to templates directory, template filename, including extension.
|
||||
// Third parameter is the layout, can be empty string.
|
||||
// Forth parameter is the bindable data to the template, can be nil.
|
||||
//
|
||||
// Use context.View to render templates to the client instead.
|
||||
// Returns an error on failure, otherwise nil.
|
||||
app.View(buff, "body.html", "", context.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.StatusCode(iris.StatusBadRequest)
|
||||
ctx.HTML("<b> Sent failed with error: " + err.Error())
|
||||
} else {
|
||||
ctx.HTML("<h1> SUCCESS </h1>")
|
||||
}
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
7
_examples/beginner/e-mail/templates/mail_body.html
Normal file
7
_examples/beginner/e-mail/templates/mail_body.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<h1>Hello From Iris web framework</h1>
|
||||
<br />
|
||||
<br />
|
||||
<span style="color: red"> {{.Message}}</span>
|
||||
<hr />
|
||||
|
||||
<b> {{.Footer}} </b>
|
||||
@@ -1,23 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
// This will serve the ./static/favicons/iris_favicon_32_32.ico to: localhost:8080/favicon.ico
|
||||
app.Favicon("./static/favicons/iris_favicon_32_32.ico")
|
||||
|
||||
// app.Favicon("./static/favicons/iris_favicon_32_32.ico", "/favicon_32_32.ico")
|
||||
// This will serve the ./static/favicons/iris_favicon_32_32.ico to: localhost:8080/favicon_32_32.ico
|
||||
// This will serve the ./static/favicons/iris_favicon_48_48.ico to: localhost:8080/favicon.ico
|
||||
app.Favicon("./static/favicons/iris_favicon_48_48.ico")
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, `You should see the favicon now at the side of your browser,
|
||||
if not, please refresh or clear the browser's cache.`)
|
||||
})
|
||||
// app.Favicon("./static/favicons/iris_favicon_48_48.ico", "/favicon_48_48.ico")
|
||||
// This will serve the ./static/favicons/iris_favicon_48_48.ico to: localhost:8080/favicon_48_48.ico
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML(`<a href="/favicon.ico"> press here to see the favicon.ico</a>.
|
||||
At some browsers like chrome, it should be visible at the top-left side of the browser's window,
|
||||
because some browsers make requests to the /favicon.ico automatically,
|
||||
so Iris serves your favicon in that path too (you can change it).`)
|
||||
}) // if favicon doesn't show to you, try to clear your browser's cache.
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -1,63 +1,49 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
var myLogFile *os.File
|
||||
// get a filename based on the date, file logs works that way the most times
|
||||
// but these are just a sugar, you can directly attach a new file logger with .AttachLogger(io.Writer)
|
||||
func todayFilename() string {
|
||||
today := time.Now().Format("Jan 02 2006")
|
||||
return today + ".txt"
|
||||
}
|
||||
|
||||
func init() {
|
||||
// open an output file
|
||||
f, err := os.Create("logs.txt")
|
||||
func newLogFile() *os.File {
|
||||
filename := todayFilename()
|
||||
// open an output file, this will append to the today's file if server restarted.
|
||||
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
myLogFile = f
|
||||
}
|
||||
|
||||
func myFileLogger() iris.LoggerPolicy {
|
||||
|
||||
// you can use a *File or an io.Writer,
|
||||
// we want to log with timestamps so we use the log.New.
|
||||
myLogger := log.New(myLogFile, "", log.LstdFlags)
|
||||
|
||||
// the logger is just a func,
|
||||
// will be used in runtime
|
||||
return func(mode iris.LogMode, message string) {
|
||||
// optionally, check for production or development log message mode
|
||||
// two modes: iris.ProdMode and iris.DevMode
|
||||
if mode == iris.ProdMode {
|
||||
// log only production-mode log messages
|
||||
myLogger.Println(message)
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func main() {
|
||||
// close the log file on exit application
|
||||
// when panic or iris exited by interupt event or manually by Shutdown.
|
||||
defer func() {
|
||||
if err := myLogFile.Close(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}()
|
||||
f := newLogFile()
|
||||
defer f.Close()
|
||||
|
||||
app := iris.New()
|
||||
app.Adapt(myFileLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
// for the sake of simplicity, in order see the logs at the ./logs.txt:
|
||||
app.Log(iris.ProdMode, "You have requested: http://localhost/8080"+ctx.Path())
|
||||
// attach the file as logger, remember, iris' app logger is just an io.Writer.
|
||||
app.AttachLogger(f)
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
// for the sake of simplicity, in order see the logs at the ./_today_.txt
|
||||
ctx.Application().Log("Request: %s\r\n", ctx.Path())
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
// open http://localhost:8080
|
||||
// and watch the ./logs.txt file
|
||||
app.Listen(":8080")
|
||||
// navigate to http://localhost:8080
|
||||
// and open the ./logs.txt file
|
||||
if err := app.Run(iris.Addr(":8080"), iris.WithoutBanner); err != nil {
|
||||
app.Log("Shutdown with error: %v", err)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
// first parameter is the request path
|
||||
// second is the operating system directory
|
||||
app.StaticWeb("/static", "./assets")
|
||||
|
||||
app.Listen(":8080")
|
||||
// http://localhost:8080/static/css/main.css
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// Adapt the "httprouter", faster,
|
||||
// but it has limits on named path parameters' validation,
|
||||
// you can adapt "gorillamux" if you need regexp path validation!
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.HandleFunc("GET", "/", func(ctx *iris.Context) {
|
||||
ctx.Writef("hello world\n")
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
||||
29
_examples/beginner/http-errors/main.go
Normal file
29
_examples/beginner/http-errors/main.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.OnErrorCode(iris.StatusInternalServerError, func(ctx context.Context) {
|
||||
ctx.HTML("Message: <b>" + ctx.Values().GetString("message") + "</b>")
|
||||
})
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML(`Click <a href="/my500">here</a> to fire the 500 status code`)
|
||||
})
|
||||
|
||||
app.Get("/my500", func(ctx context.Context) {
|
||||
ctx.Values().Set("message", "this is the error message")
|
||||
ctx.StatusCode(500)
|
||||
})
|
||||
|
||||
app.Get("/u/{firstname:alphabetical}", func(ctx context.Context) {
|
||||
ctx.Writef("Hello %s", ctx.Values().GetString("firstname"))
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// Package main provide one-line integration with letsencrypt.org
|
||||
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("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from SECURE SERVER!")
|
||||
})
|
||||
|
||||
app.Get("/test2", func(ctx *iris.Context) {
|
||||
ctx.Writef("Welcome to secure server from /test2!")
|
||||
})
|
||||
|
||||
app.Get("/redirect", func(ctx *iris.Context) {
|
||||
ctx.Redirect("/test2")
|
||||
})
|
||||
|
||||
// This will provide you automatic certification & key from letsencrypt.org's servers
|
||||
// it also starts a second 'http://' server which will redirect all 'http://$PATH' requests to 'https://$PATH'
|
||||
|
||||
// NOTE: may not work on local addresses like this,
|
||||
// use it on a real domain, because
|
||||
// it uses the "golang.org/x/crypto/acme/autocert" package.
|
||||
app.ListenLETSENCRYPT("localhost:443")
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
const host = "127.0.0.1:443"
|
||||
|
||||
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 SECURE server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from the SECURE server on path /mypath")
|
||||
})
|
||||
|
||||
// start a secondary server (HTTP) on port 80, this is a non-blocking func
|
||||
// redirects all http to the main server which is tls/ssl on port :443
|
||||
|
||||
iris.Proxy(":80", "https://"+host)
|
||||
// start the MAIN server (HTTPS) on port 443, this is a blocking func
|
||||
app.ListenTLS(host, "mycert.cert", "mykey.key")
|
||||
|
||||
// now if you navigate to http://127.0.0.1/mypath it will
|
||||
// send you back to https://127.0.0.1:443/mypath (https://127.0.0.1/mypath)
|
||||
//
|
||||
// go to the listen-letsencrypt example to view how you can integrate your server
|
||||
// to get automatic certification and key from the letsencrypt.org 's servers.
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
const host = "127.0.0.1:443"
|
||||
|
||||
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.ListenUNIX("/tmp/srv.sock", 0666)
|
||||
}
|
||||
29
_examples/beginner/listening/custom-listener/main.go
Normal file
29
_examples/beginner/listening/custom-listener/main.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"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())
|
||||
})
|
||||
|
||||
// create any custom tcp listener, unix sock file or tls tcp listener.
|
||||
l, err := net.Listen("tcp4", ":8080")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// use of the custom listener
|
||||
app.Run(iris.Listener(l))
|
||||
}
|
||||
19
_examples/beginner/listening/listen-addr/main.go
Normal file
19
_examples/beginner/listening/listen-addr/main.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("<h1>Index /</h1>")
|
||||
})
|
||||
|
||||
if err := app.Run(iris.Addr(":8080")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
}
|
||||
31
_examples/beginner/listening/listen-letsencrypt/main.go
Normal file
31
_examples/beginner/listening/listen-letsencrypt/main.go
Normal file
@@ -0,0 +1,31 @@
|
||||
// Package main provide one-line integration with letsencrypt.org
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from SECURE SERVER!")
|
||||
})
|
||||
|
||||
app.Get("/test2", func(ctx context.Context) {
|
||||
ctx.Writef("Welcome to secure server from /test2!")
|
||||
})
|
||||
|
||||
app.Get("/redirect", func(ctx context.Context) {
|
||||
ctx.Redirect("/test2")
|
||||
})
|
||||
|
||||
// If http to https auto-redirect is one of your needs
|
||||
// please look the code inside iris_deprecateed.go.ListenLETSENCRYPT to do it manually.
|
||||
|
||||
// NOTE: This may not work on local addresses like this,
|
||||
// use it on a real domain, because
|
||||
// it uses the "golang.org/x/crypto/acme/autocert" package.
|
||||
app.Run(iris.AutoTLS("localhost:443"))
|
||||
}
|
||||
21
_examples/beginner/listening/listen-tls/main.go
Normal file
21
_examples/beginner/listening/listen-tls/main.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"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 SECURE server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the SECURE server on path /mypath")
|
||||
})
|
||||
|
||||
// start the server (HTTPS) on port 443, this is a blocking func
|
||||
app.Run(iris.TLS("127.0.0.1:443", "mycert.cert", "mykey.key"))
|
||||
}
|
||||
17
_examples/beginner/listening/listen-unix/main.go
Normal file
17
_examples/beginner/listening/listen-unix/main.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/core/nettools"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
l, err := nettools.UNIX("/tmpl/srv.sock", 0666) // see its code to see how you can manually create a new file listener, it's easy.
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
app.Run(iris.Listener(l))
|
||||
}
|
||||
117
_examples/beginner/overview/main.go
Normal file
117
_examples/beginner/overview/main.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
// User is just a bindable object structure.
|
||||
type User struct {
|
||||
Username string `json:"username"`
|
||||
Firstname string `json:"firstname"`
|
||||
Lastname string `json:"lastname"`
|
||||
City string `json:"city"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// Define templates using the std html/template engine.
|
||||
// Parse and load all files inside "./views" folder with ".html" file extension.
|
||||
// Reload the templates on each request (development mode).
|
||||
app.AttachView(view.HTML("./views", ".html").Reload(true))
|
||||
|
||||
// Regster custom handler for specific http errors.
|
||||
app.OnErrorCode(iris.StatusInternalServerError, func(ctx context.Context) {
|
||||
// .Values are used to communicate between handlers, middleware.
|
||||
errMessage := ctx.Values().GetString("error")
|
||||
if errMessage != "" {
|
||||
ctx.Writef("Internal server error: %s", errMessage)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Writef("(Unexpected) internal server error")
|
||||
})
|
||||
|
||||
app.Use(func(ctx context.Context) {
|
||||
ctx.Application().Log("Begin request for path: %s", ctx.Path())
|
||||
ctx.Next()
|
||||
})
|
||||
|
||||
// app.Done(func(ctx context.Context) {]})
|
||||
|
||||
// Method POST: http://localhost:8080/decode
|
||||
app.Post("/decode", func(ctx context.Context) {
|
||||
var user User
|
||||
ctx.ReadJSON(&user)
|
||||
ctx.Writef("%s %s is %d years old and comes from %s", user.Firstname, user.Lastname, user.Age, user.City)
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/encode
|
||||
app.Get("/encode", func(ctx context.Context) {
|
||||
doe := User{
|
||||
Username: "Johndoe",
|
||||
Firstname: "John",
|
||||
Lastname: "Doe",
|
||||
City: "Neither FBI knows!!!",
|
||||
Age: 25,
|
||||
}
|
||||
|
||||
ctx.JSON(doe)
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/profile/anytypeofstring
|
||||
app.Get("/profile/{username:string}", profileByUsername)
|
||||
|
||||
usersRoutes := app.Party("/users", logThisMiddleware)
|
||||
{
|
||||
// Method GET: http://localhost:8080/users/42
|
||||
usersRoutes.Get("/{id:int min(1)}", getUserByID)
|
||||
// Method POST: http://localhost:8080/users/create
|
||||
usersRoutes.Post("/create", createUser)
|
||||
}
|
||||
|
||||
// Listen for incoming HTTP/1.x & HTTP/2 clients on localhost port 8080.
|
||||
app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8"))
|
||||
}
|
||||
|
||||
func logThisMiddleware(ctx context.Context) {
|
||||
ctx.Application().Log("Path: %s | IP: %s", ctx.Path(), ctx.RemoteAddr())
|
||||
|
||||
// .Next is required to move forward to the chain of handlers,
|
||||
// if missing then it stops the execution at this handler.
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
func profileByUsername(ctx context.Context) {
|
||||
// .Params are used to get dynamic path parameters.
|
||||
username := ctx.Params().Get("username")
|
||||
ctx.ViewData("Username", username)
|
||||
// renders "./views/users/profile.html"
|
||||
// with {{ .Username }} equals to the username dynamic path parameter.
|
||||
ctx.View("users/profile.html")
|
||||
}
|
||||
|
||||
func getUserByID(ctx context.Context) {
|
||||
userID := ctx.Params().Get("id") // Or convert directly using: .Values().GetInt/GetInt64 etc...
|
||||
// your own db fetch here instead of user :=...
|
||||
user := User{Username: "username" + userID}
|
||||
|
||||
ctx.XML(user)
|
||||
}
|
||||
|
||||
func createUser(ctx context.Context) {
|
||||
var user User
|
||||
err := ctx.ReadForm(&user)
|
||||
if err != nil {
|
||||
ctx.Values().Set("error", "creating user, read and parse form failed. "+err.Error())
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// renders "./views/users/create_verification.html"
|
||||
// with {{ . }} equals to the User object, i.e {{ .Username }} , {{ .Firstname}} etc...
|
||||
ctx.ViewData("", user)
|
||||
ctx.View("users/create_verification.html")
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<html>
|
||||
<head><title>Create verification</title></head>
|
||||
<body>
|
||||
<h1> Create Verification </h1>
|
||||
<table style="width:550px">
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>City</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>{{ .Username }}</td>
|
||||
<td>{{ .Firstname }}</td>
|
||||
<td>{{ .Lastname }}</td>
|
||||
<td>{{ .City }}</td>
|
||||
<td>{{ .Age }}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
7
_examples/beginner/overview/views/users/profile.html
Normal file
7
_examples/beginner/overview/views/users/profile.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<html>
|
||||
<head><title>Profile page</title></head>
|
||||
<body>
|
||||
<h1> Profile </h1>
|
||||
<b> {{ .Username }} </b>
|
||||
</body>
|
||||
</html>
|
||||
20
_examples/beginner/pprof/main.go
Normal file
20
_examples/beginner/pprof/main.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/middleware/pprof"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("<h1> Please click <a href='/debug/pprof'>here</a>")
|
||||
})
|
||||
|
||||
app.Any("/debug/pprof/{action:path}", pprof.New())
|
||||
// ___________
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -2,9 +2,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 Visitor struct {
|
||||
@@ -15,28 +15,27 @@ type Visitor struct {
|
||||
|
||||
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())
|
||||
// set the view html template engine
|
||||
app.AttachView(view.HTML("./templates", ".html").Reload(true))
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
if err := ctx.View("form.html"); err != nil {
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.WriteString(err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
app.Post("/form_action", func(ctx *iris.Context) {
|
||||
app.Post("/form_action", func(ctx context.Context) {
|
||||
visitor := Visitor{}
|
||||
err := ctx.ReadForm(&visitor)
|
||||
if err != nil {
|
||||
ctx.Log(iris.DevMode, "Error when reading form: "+err.Error())
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.WriteString(err.Error())
|
||||
}
|
||||
|
||||
ctx.Writef("Visitor: %#v", visitor)
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -4,13 +4,16 @@
|
||||
</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">
|
||||
Username: <input type="text" name="Username" /> <br />
|
||||
Mail: <input type="text" name="Mail" /> <br />
|
||||
Select one or more: <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" />
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
type Company struct {
|
||||
@@ -11,26 +11,34 @@ type Company struct {
|
||||
Other string
|
||||
}
|
||||
|
||||
func MyHandler(ctx *iris.Context) {
|
||||
func MyHandler(ctx context.Context) {
|
||||
c := &Company{}
|
||||
if err := ctx.ReadJSON(c); err != nil {
|
||||
ctx.Log(iris.DevMode, err.Error())
|
||||
ctx.StatusCode(iris.StatusBadRequest)
|
||||
ctx.WriteString(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Writef("Company: %#v\n", c)
|
||||
ctx.Writef("Received: %#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")
|
||||
|
||||
// use Postman or whatever to do a POST request
|
||||
// to the http://localhost:8080 with RAW BODY:
|
||||
/*
|
||||
{
|
||||
"Name": "Iris-Go",
|
||||
"City": "New York",
|
||||
"Other": "Something here"
|
||||
}
|
||||
*/
|
||||
// and Content-Type to application/json
|
||||
//
|
||||
// The response should be:
|
||||
// Received: &main.Company{Name:"Iris-Go", City:"New York", Other:"Something here"}
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
30
_examples/beginner/recover/main.go
Normal file
30
_examples/beginner/recover/main.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/middleware/recover"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// use this recover(y) middleware
|
||||
app.Use(recover.New())
|
||||
|
||||
i := 0
|
||||
// let's simmilate a panic every next request
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
i++
|
||||
if i%2 == 0 {
|
||||
panic("a panic here")
|
||||
}
|
||||
ctx.Writef("Hello, refresh one time more to get panic!")
|
||||
})
|
||||
|
||||
// http://localhost:8080, refresh it 5-6 times.
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
// Note:
|
||||
// app := iris.Default() instead of iris.New() makes use of the recovery middleware automatically.
|
||||
52
_examples/beginner/request-logger/main.go
Normal file
52
_examples/beginner/request-logger/main.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/middleware/logger"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.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 context.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
app.Get("/1", func(ctx context.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
app.Get("/2", func(ctx context.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
// log http errors should be done manually
|
||||
errorLogger := logger.New()
|
||||
|
||||
app.OnErrorCode(iris.StatusNotFound, func(ctx context.Context) {
|
||||
errorLogger(ctx)
|
||||
ctx.Writef("My Custom 404 error page ")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/1
|
||||
// http://localhost:8080/2
|
||||
// http://lcoalhost:8080/notfoundhere
|
||||
// see the output on the console.
|
||||
app.Run(iris.Addr(":8080"))
|
||||
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/gorillamux" // import the gorillamux adaptor
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // writes both prod and dev logs to the os.Stdout
|
||||
app.Adapt(gorillamux.New()) // uses the gorillamux for routing and reverse routing
|
||||
|
||||
// set a custom 404 handler
|
||||
app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusNotFound, "<h1> custom http error page </h1>")
|
||||
})
|
||||
|
||||
app.Get("/healthcheck", h)
|
||||
|
||||
gamesMiddleware := func(ctx *iris.Context) {
|
||||
println(ctx.Method() + ": " + ctx.Path())
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
games := app.Party("/games", gamesMiddleware)
|
||||
{ // braces are optional of course, it's just a style of code
|
||||
games.Get("/{gameID:[0-9]+}/clans", h)
|
||||
games.Get("/{gameID:[0-9]+}/clans/clan/{publicID:[0-9]+}", h)
|
||||
games.Get("/{gameID:[0-9]+}/clans/search", h)
|
||||
|
||||
games.Put("/{gameID:[0-9]+}/players/{publicID:[0-9]+}", h)
|
||||
games.Put("/{gameID:[0-9]+}/clans/clan/{publicID:[0-9]+}", h)
|
||||
|
||||
games.Post("/{gameID:[0-9]+}/clans", h)
|
||||
games.Post("/{gameID:[0-9]+}/players", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{publicID:[0-9]+}/leave", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/application", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/application/:action", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/invitation", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/invitation/:action", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/delete", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/promote", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/demote", h)
|
||||
}
|
||||
|
||||
myroute := app.Get("/anything/{anythingparameter:.*}", func(ctx *iris.Context) {
|
||||
s := ctx.Param("anythingparameter")
|
||||
ctx.Writef("The path after /anything is: %s", s)
|
||||
}) // .ChangeName("myroute")
|
||||
|
||||
app.Get("/reverse_myroute", func(ctx *iris.Context) {
|
||||
// reverse routing snippet using templates:
|
||||
// https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_3 (gorillamux)
|
||||
// https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_4 (httprouter)
|
||||
|
||||
myrouteRequestPath := app.Path(myroute.Name(), "anythingparameter", "something/here")
|
||||
ctx.Writef("Should be '/anything/something/here': %s", myrouteRequestPath)
|
||||
})
|
||||
|
||||
p := app.Party("mysubdomain.")
|
||||
// http://mysubdomain.myhost.com/
|
||||
p.Get("/", h)
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
||||
|
||||
func h(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, "<h1>Path<h1/>"+ctx.Path())
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func hello(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusNotFound, "<h1>Custom not found handler </h1>")
|
||||
})
|
||||
|
||||
app.Get("/", hello)
|
||||
app.Get("/users/:userid", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello user with id: %s", ctx.Param("userid"))
|
||||
})
|
||||
|
||||
app.Get("/myfiles/*file", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, "Hello, the dynamic path after /myfiles is:<br/> <b>"+ctx.Param("file")+"</b>")
|
||||
})
|
||||
|
||||
app.Get("/users/:userid/messages/:messageid", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, `Message from user with id:<br/> <b>`+ctx.Param("userid")+`</b>,
|
||||
message id: <b>`+ctx.Param("messageid")+`</b>`)
|
||||
})
|
||||
|
||||
// http://127.0.0.1:8080/users/42
|
||||
// http://127.0.0.1:8080/myfiles/mydirectory/myfile.zip
|
||||
// http://127.0.0.1:8080/users/42/messages/1
|
||||
app.Listen(":8080")
|
||||
}
|
||||
170
_examples/beginner/routing/basic/main.go
Normal file
170
_examples/beginner/routing/basic/main.go
Normal file
@@ -0,0 +1,170 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// registers a custom handler for 404 not found http (error) status code,
|
||||
// fires when route not found or manually by ctx.StatusCode(iris.StatusNotFound).
|
||||
app.OnErrorCode(iris.StatusNotFound, notFoundHandler)
|
||||
|
||||
// GET -> HTTP Method
|
||||
// / -> Path
|
||||
// func(ctx context.Context) -> The route's handler.
|
||||
//
|
||||
// Third receiver should contains the route's handler(s), they are executed by order.
|
||||
app.Handle("GET", "/", func(ctx context.Context) {
|
||||
// navigate to the middle of $GOPATH/src/github.com/kataras/iris/context/context.go
|
||||
// to overview all context's method (there a lot of them, read that and you will learn how iris works too)
|
||||
ctx.HTML("Hello from " + ctx.Path()) // Hello from /
|
||||
})
|
||||
|
||||
app.Get("/home", func(ctx context.Context) {
|
||||
ctx.Writef(`Same as app.Handle("GET", "/", [...])`)
|
||||
})
|
||||
|
||||
app.Get("/donate", donateHandler, donateFinishHandler)
|
||||
|
||||
// Pssst, don't forget dynamic-path example for more "magic"!
|
||||
app.Get("/api/users/{userid:int min(1)}", func(ctx context.Context) {
|
||||
userID, err := ctx.Params().GetInt("userid")
|
||||
|
||||
if err != nil {
|
||||
ctx.Writef("error while trying to parse userid parameter," +
|
||||
"this will never happen if :int is being used because if it's not integer it will fire Not Found automatically.")
|
||||
ctx.StatusCode(iris.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(map[string]interface{}{
|
||||
// you can pass any custom structured go value of course.
|
||||
"user_id": userID,
|
||||
})
|
||||
})
|
||||
// app.Post("/", func(ctx context.Context){}) -> for POST http method.
|
||||
// app.Put("/", func(ctx context.Context){})-> for "PUT" http method.
|
||||
// app.Delete("/", func(ctx context.Context){})-> for "DELETE" http method.
|
||||
// app.Options("/", func(ctx context.Context){})-> for "OPTIONS" http method.
|
||||
// app.Trace("/", func(ctx context.Context){})-> for "TRACE" http method.
|
||||
// app.Head("/", func(ctx context.Context){})-> for "HEAD" http method.
|
||||
// app.Connect("/", func(ctx context.Context){})-> for "CONNECT" http method.
|
||||
// app.Patch("/", func(ctx context.Context){})-> for "PATCH" http method.
|
||||
// app.Any("/", func(ctx context.Context){}) for all http methods.
|
||||
|
||||
// More than one route can contain the same path with a different http mapped method.
|
||||
// You can catch any route creation errors with:
|
||||
// route, err := app.Get(...)
|
||||
// set a name to a route: route.Name = "myroute"
|
||||
|
||||
// You can also group routes by path prefix, sharing middleware(s) and done handlers.
|
||||
|
||||
adminRoutes := app.Party("/admin", adminMiddleware)
|
||||
|
||||
adminRoutes.Done(func(ctx context.Context) { // executes always last if ctx.Next()
|
||||
ctx.Application().Log("response sent to " + ctx.Path())
|
||||
})
|
||||
// adminRoutes.Layout("/views/layouts/admin.html") // set a view layout for these routes, see more at intermediate/view examples.
|
||||
|
||||
// GET: http://localhost:8080/admin
|
||||
adminRoutes.Get("/", func(ctx context.Context) {
|
||||
// [...]
|
||||
ctx.StatusCode(iris.StatusOK) // default is 200 == iris.StatusOK
|
||||
ctx.HTML("<h1>Hello from admin/</h1>")
|
||||
|
||||
ctx.Next() // in order to execute the party's "Done" Handler(s)
|
||||
})
|
||||
|
||||
// GET: http://localhost:8080/admin/login
|
||||
adminRoutes.Get("/login", func(ctx context.Context) {
|
||||
// [...]
|
||||
})
|
||||
// POST: http://localhost:8080/admin/login
|
||||
adminRoutes.Post("/login", func(ctx context.Context) {
|
||||
// [...]
|
||||
})
|
||||
|
||||
// subdomains, easier than ever, should add localhost or 127.0.0.1 into your hosts file,
|
||||
// etc/hosts on unix or C:/windows/system32/drivers/etc/hosts on windows.
|
||||
v1 := app.Party("v1.")
|
||||
{ // braces are optional, it's just type of style, to group the routes visually.
|
||||
|
||||
// http://v1.localhost:8080
|
||||
v1.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("Version 1 API. go to <a href='" + ctx.Path() + "/api" + "'>/api/users</a>")
|
||||
})
|
||||
|
||||
usersAPI := v1.Party("/api/users")
|
||||
{
|
||||
// http://v1.localhost:8080/api/users
|
||||
usersAPI.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("All users")
|
||||
})
|
||||
// http://v1.localhost:8080/api/users/42
|
||||
usersAPI.Get("/{userid:int}", func(ctx context.Context) {
|
||||
ctx.Writef("user with id: %s", ctx.Params().Get("userid"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// wildcard subdomains.
|
||||
wildcardSubdomain := app.Party("*.")
|
||||
{
|
||||
wildcardSubdomain.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Subdomain can be anything, now you're here from: %s", ctx.Subdomain())
|
||||
})
|
||||
}
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/home
|
||||
// http://localhost:8080/donate
|
||||
// http://localhost:8080/api/users/42
|
||||
// http://localhost:8080/admin
|
||||
// http://localhost:8080/admin/login
|
||||
//
|
||||
// http://localhost:8080/api/users/0
|
||||
// http://localhost:8080/api/users/blabla
|
||||
// http://localhost:8080/wontfound
|
||||
//
|
||||
// if hosts edited:
|
||||
// http://v1.localhost:8080
|
||||
// http://v1.localhost:8080/api/users
|
||||
// http://v1.localhost:8080/api/users/42
|
||||
// http://anything.localhost:8080
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func adminMiddleware(ctx context.Context) {
|
||||
// [...]
|
||||
ctx.Next() // to move to the next handler, or don't that if you have any auth logic.
|
||||
}
|
||||
|
||||
func donateHandler(ctx context.Context) {
|
||||
ctx.Writef("Just like an inline handler, but it can be " +
|
||||
"used by other package, anywhere in your project.")
|
||||
|
||||
// let's pass a value to the next handler
|
||||
// Values is the way handlers(or middleware) are communicating between each other.
|
||||
ctx.Values().Set("donate_url", "https://github.com/kataras/iris#buy-me-a-cup-of-coffee")
|
||||
ctx.Next() // in order to execute the next handler in the chain, look donate route.
|
||||
}
|
||||
|
||||
func donateFinishHandler(ctx context.Context) {
|
||||
// values can be any type of object so we could cast the value to a string
|
||||
// but Iris provides an easy to do that, if donate_url is not defined, then it returns an empty string instead.
|
||||
donateURL := ctx.Values().GetString("donate_url")
|
||||
ctx.Application().Log("donate_url value was: " + donateURL)
|
||||
ctx.Writef("\n\nDonate sent(?).")
|
||||
}
|
||||
|
||||
func notFoundHandler(ctx context.Context) {
|
||||
ctx.HTML("Custom route for 404 not found http code, here you can render a view, html, json <b>any valid response</b>.")
|
||||
}
|
||||
|
||||
// Notes:
|
||||
// A path parameter name should contain only alphabetical letters, symbols, containing '_' and numbers are NOT allowed.
|
||||
// If route failed to be registered, the app will panic without any warnings
|
||||
// if you didn't catch the second return value(error) on .Handle/.Get....
|
||||
183
_examples/beginner/routing/dynamic-path/main.go
Normal file
183
_examples/beginner/routing/dynamic-path/main.go
Normal file
@@ -0,0 +1,183 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// At the previous example "routing/basic",
|
||||
// we've seen static routes, group of routes, subdomains, wildcard subdomains, a small example of parameterized path
|
||||
// with a single known paramete and custom http errors, now it's time to see wildcard parameters and macros.
|
||||
|
||||
// Iris, like net/http std package registers route's handlers
|
||||
// by a Handler, the Iris' type of handler is just a func(ctx context.Context)
|
||||
// where context comes from github.com/kataras/iris/context.
|
||||
// Until go 1.9 you will have to import that package too, after go 1.9 this will be not be necessary.
|
||||
//
|
||||
// Iris has the easiest and the most powerful routing process you have ever meet.
|
||||
// If you're used to use the "httprouter"
|
||||
// then you don't have to change a thing of a route's path.
|
||||
//
|
||||
// At the same time,
|
||||
// Iris has its own interpeter(yes like a programming language)
|
||||
// for route's path syntax and their dynamic path parameters parsing and evaluation,
|
||||
// I am calling them "macros" for shortcut.
|
||||
// In the following examples we will see only the second option, which has exactly the same speed
|
||||
// compared to "httprouter".
|
||||
// How? It calculates its needs and if not any special regexp needed then it just
|
||||
// registers the route with the underline httprouter's path syntax,
|
||||
// otherwise it pre-compiles the regexp and adds the necessary middleware(s).
|
||||
//
|
||||
// Note: the Iris' router follows the "httprouter"'s rules for routes confliction.
|
||||
//
|
||||
// Standard macro types for parameters:
|
||||
// +------------------------+
|
||||
// | {param:string} |
|
||||
// +------------------------+
|
||||
// string type
|
||||
// anything
|
||||
//
|
||||
// +------------------------+
|
||||
// | {param:int} |
|
||||
// +------------------------+
|
||||
// int type
|
||||
// only numbers (0-9)
|
||||
//
|
||||
// +------------------------+
|
||||
// | {param:alphabetical} |
|
||||
// +------------------------+
|
||||
// alphabetical/letter type
|
||||
// letters only (upper or lowercase)
|
||||
//
|
||||
// +------------------------+
|
||||
// | {param:file} |
|
||||
// +------------------------+
|
||||
// file type
|
||||
// letters (upper or lowercase)
|
||||
// numbers (0-9)
|
||||
// underscore (_)
|
||||
// dash (-)
|
||||
// point (.)
|
||||
// no spaces ! or other character
|
||||
//
|
||||
// +------------------------+
|
||||
// | {param:path} |
|
||||
// +------------------------+
|
||||
// path type
|
||||
// anything, should be the last part, more than one path segment,
|
||||
// i.e: /path1/path2/path3 , ctx.Params().GetString("param") == "/path1/path2/path3"
|
||||
//
|
||||
// if type is missing then parameter's type is defaulted to string, so
|
||||
// {param} == {param:string}.
|
||||
//
|
||||
// If a function not found on that type then the "string"'s types functions are being used.
|
||||
// i.e:
|
||||
// {param:int min(3)}
|
||||
//
|
||||
//
|
||||
// Besides the fact that Iris provides the basic types and some default "macro funcs"
|
||||
// you are able to register your own too!.
|
||||
//
|
||||
// Register a named path parameter function:
|
||||
// app.Macros().Int.RegisterFunc("min", func(argument int) func(paramValue string) bool {
|
||||
// [...]
|
||||
// return true/false -> true means valid.
|
||||
// })
|
||||
//
|
||||
// at the func(argument ...) you can have any standard type, it will be validated before the server starts
|
||||
// so don't care about performance here, the only thing it runs at serve time is the returning func(paramValue string) bool.
|
||||
//
|
||||
// {param:string equal(iris)} , "iris" will be the argument here:
|
||||
// app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool {
|
||||
// return func(paramValue string){ return argument == paramValue }
|
||||
// })
|
||||
|
||||
// you can use the "string" type which is valid for a single path parameter that can be anything.
|
||||
app.Get("/username/{name}", func(ctx context.Context) {
|
||||
ctx.Writef("Hello %s", ctx.Params().Get("name"))
|
||||
}) // type is missing = {name:string}
|
||||
|
||||
// Let's register our first macro attached to int macro type.
|
||||
// "min" = the function
|
||||
// "minValue" = the argument of the function
|
||||
// func(string) bool = the macro's path parameter evaluator, this executes in serve time when
|
||||
// a user requests a path which contains the :int macro type with the min(...) macro parameter function.
|
||||
app.Macros().Int.RegisterFunc("min", func(minValue int) func(string) bool {
|
||||
// do anything before serve here [...]
|
||||
// at this case we don't need to do anything
|
||||
return func(paramValue string) bool {
|
||||
n, err := strconv.Atoi(paramValue)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return n >= minValue
|
||||
}
|
||||
})
|
||||
|
||||
// http://localhost:8080/profile/id>=1
|
||||
// this will throw 404 even if it's found as route on : /profile/0, /profile/blabla, /profile/-1
|
||||
// macro parameter functions are optional of course.
|
||||
app.Get("/profile/{id:int min(1)}", func(ctx context.Context) {
|
||||
// second parameter is the error but it will always nil because we use macros,
|
||||
// the validaton already happened.
|
||||
id, _ := ctx.Params().GetInt("id")
|
||||
ctx.Writef("Hello id: %d", id)
|
||||
})
|
||||
|
||||
// to change the error code per route's macro evaluator:
|
||||
app.Get("/profile/{id:int min(1)}/friends/{friendid:int min(1) else 504}", func(ctx context.Context) {
|
||||
id, _ := ctx.Params().GetInt("id")
|
||||
friendid, _ := ctx.Params().GetInt("friendid")
|
||||
ctx.Writef("Hello id: %d looking for friend id: ", id, friendid)
|
||||
}) // this will throw e 504 error code instead of 404 if all route's macros not passed.
|
||||
|
||||
// http://localhost:8080/game/a-zA-Z/level/0-9
|
||||
// remember, alphabetical is lowercase or uppercase letters only.
|
||||
app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx context.Context) {
|
||||
ctx.Writef("name: %s | level: %s", ctx.Params().Get("name"), ctx.Params().Get("level"))
|
||||
})
|
||||
|
||||
// let's use a trivial custom regexp that validates a single path parameter
|
||||
// which its value is only lowercase letters.
|
||||
|
||||
// http://localhost:8080/lowercase/kataras
|
||||
app.Get("/lowercase/{name:string regexp(^[a-z]+)}", func(ctx context.Context) {
|
||||
ctx.Writef("name should be only lowercase, otherwise this handler will never executed: %s", ctx.Params().Get("name"))
|
||||
})
|
||||
|
||||
// http://localhost:8080/single_file/app.js
|
||||
app.Get("/single_file/{myfile:file}", func(ctx context.Context) {
|
||||
ctx.Writef("file type validates if the parameter value has a form of a file name, got: %s", ctx.Params().Get("myfile"))
|
||||
})
|
||||
|
||||
// http://localhost:8080/myfiles/any/directory/here/
|
||||
// this is the only macro type that accepts any number of path segments.
|
||||
app.Get("/myfiles/{directory:path}", func(ctx context.Context) {
|
||||
ctx.Writef("path type accepts any number of path segments, path after /myfiles/ is: %s", ctx.Params().Get("directory"))
|
||||
}) // for wildcard path (any number of path segments) without validation you can use:
|
||||
// /myfiles/*directory
|
||||
|
||||
// "{param}"'s performance is exactly the same of ":param"'s.
|
||||
|
||||
// alternatives -> ":param" for single path parameter and "*paramPath" for wildcard path parameter
|
||||
// acquire them by ctx.Params().Get as always.
|
||||
|
||||
// WARNING:
|
||||
// A path parameter name should contain only alphabetical letters, symbols, containing '_' and numbers are NOT allowed.
|
||||
// If route failed to be registered, the app will panic without any warnings
|
||||
// if you didn't catch the second return value(error) on .Handle/.Get....
|
||||
|
||||
// Last, do not confuse ctx.Values() with ctx.Params().
|
||||
// Path parameter's values goes to ctx.Params() and context's local storage
|
||||
// that can be used to communicate between handlers and middleware(s) goes to
|
||||
// ctx.Values(), path parameters and the rest of any custom values are separated for your own good.
|
||||
|
||||
if err := app.Run(iris.Addr(":8080")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
107
_examples/beginner/routing/main.go
Normal file
107
_examples/beginner/routing/main.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
/*
|
||||
Read:
|
||||
"basic"
|
||||
"dynamic-path"
|
||||
and "reverse" examples if you want to release Iris' real power.
|
||||
*/
|
||||
|
||||
const maxBodySize = 1 << 20
|
||||
|
||||
var app *iris.Application
|
||||
|
||||
func init() {
|
||||
app = iris.New()
|
||||
}
|
||||
|
||||
func registerErrors() {
|
||||
// set a custom 404 handler
|
||||
app.OnErrorCode(iris.StatusNotFound, func(ctx context.Context) {
|
||||
ctx.HTML("<h1> custom http error page </h1>")
|
||||
})
|
||||
}
|
||||
|
||||
func registerGamesRoutes() {
|
||||
gamesMiddleware := func(ctx context.Context) {
|
||||
println(ctx.Method() + ": " + ctx.Path())
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// party is just a group of routes with the same prefix
|
||||
// and middleware, i.e: "/games" and gamesMiddleware.
|
||||
games := app.Party("/games", gamesMiddleware)
|
||||
{ // braces are optional of course, it's just a style of code
|
||||
|
||||
// "GET" method
|
||||
games.Get("/{gameID:int}/clans", h)
|
||||
games.Get("/{gameID:int}/clans/clan/{clanPublicID:int}", h)
|
||||
games.Get("/{gameID:int}/clans/search", h)
|
||||
|
||||
// "PUT" method
|
||||
games.Put("/{gameID:int}/players/{clanPublicID:int}", h)
|
||||
games.Put("/{gameID:int}/clans/clan/{clanPublicID:int}", h)
|
||||
// remember: "clanPublicID" should not be changed to other routes with the same prefix.
|
||||
// "POST" method
|
||||
games.Post("/{gameID:int}/clans", h)
|
||||
games.Post("/{gameID:int}/players", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/leave", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/application", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/application/{action}", h) // {action} == {action:string}
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/invitation", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/invitation/{action}", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/delete", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/promote", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/demote", h)
|
||||
}
|
||||
}
|
||||
|
||||
func registerSubdomains() {
|
||||
mysubdomain := app.Party("mysubdomain.")
|
||||
// http://mysubdomain.myhost.com
|
||||
mysubdomain.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from subdomain: %s , from host: %s, method: %s and path: %s", ctx.Subdomain(), ctx.Host(), ctx.Method(), ctx.Path())
|
||||
})
|
||||
}
|
||||
func main() {
|
||||
registerErrors()
|
||||
registerGamesRoutes()
|
||||
registerSubdomains()
|
||||
|
||||
// more random examples below:
|
||||
|
||||
app.Handle("GET", "/healthcheck", h)
|
||||
|
||||
// "POST" method
|
||||
// this handler reads raw body from the client/request
|
||||
// and sends back the same body
|
||||
// remember, we have limit to that body in order
|
||||
// to protect ourselves from "over heating".
|
||||
app.Post("/", func(ctx context.Context) {
|
||||
ctx.SetMaxRequestBodySize(maxBodySize) // set max request body that client can send.
|
||||
// get request body
|
||||
b, err := ioutil.ReadAll(ctx.Request().Body)
|
||||
// if is larger then send a bad request status
|
||||
if err != nil {
|
||||
ctx.StatusCode(iris.StatusBadRequest)
|
||||
ctx.Writef(err.Error())
|
||||
return
|
||||
}
|
||||
// send back the post body
|
||||
ctx.Write(b)
|
||||
})
|
||||
|
||||
// start the server on 0.0.0.0:8080
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func h(ctx context.Context) {
|
||||
ctx.HTML("<h1>Path: " + ctx.Path() + "</h1>")
|
||||
}
|
||||
35
_examples/beginner/routing/reverse/main.go
Normal file
35
_examples/beginner/routing/reverse/main.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/router"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// need for manually reverse routing when needed outside of view engine.
|
||||
// you normally don't need it because of the {{ urlpath "routename" "path" "values" "here"}}
|
||||
rv := router.NewRoutePathReverser(app)
|
||||
|
||||
myroute, _ := app.Get("/anything/{anythingparameter:path}", func(ctx context.Context) {
|
||||
paramValue := ctx.Params().Get("anythingparameter")
|
||||
ctx.Writef("The path after /anything is: %s", paramValue)
|
||||
})
|
||||
|
||||
// useful for links, altough iris' view engine has the {{ urlpath "routename" "path values"}} already.
|
||||
app.Get("/reverse_myroute", func(ctx context.Context) {
|
||||
myrouteRequestPath := rv.Path(myroute.Name, "any/path")
|
||||
ctx.HTML("Should be <b>/anything/any/path</b>: " + myrouteRequestPath)
|
||||
})
|
||||
|
||||
// execute a route, similar to redirect but without redirect :)
|
||||
app.Get("/execute_myroute", func(ctx context.Context) {
|
||||
ctx.Exec("GET", "/anything/any/path") // like it was called by the client.
|
||||
})
|
||||
|
||||
// http://localhost:8080/reverse_myroute
|
||||
// http://localhost:8080/execute_myroute
|
||||
// http://localhost:8080/anything/any/path/here
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -1,21 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
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) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
file := "./files/first.zip"
|
||||
c.SendFile(file, "c.zip")
|
||||
ctx.SendFile(file, "c.zip")
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
@@ -5,20 +5,16 @@ import (
|
||||
"io"
|
||||
"time" // showcase the delay
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
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())
|
||||
|
||||
timeWaitForCloseStream := 4 * time.Second
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
i := 0
|
||||
// goroutine in order to no block and just wait,
|
||||
// goroutine is OPTIONAL and not a very good option but it depends on the needs
|
||||
@@ -39,7 +35,7 @@ func main() {
|
||||
time.Sleep(timeWaitForCloseStream)
|
||||
})
|
||||
|
||||
app.Get("/alternative", func(ctx *iris.Context) {
|
||||
app.Get("/alternative", func(ctx context.Context) {
|
||||
// Send the response in chunks and wait for a second between each chunk.
|
||||
ctx.StreamWriter(func(w io.Writer) bool {
|
||||
for i := 1; i <= 4; i++ {
|
||||
@@ -52,5 +48,5 @@ func main() {
|
||||
})
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
70
_examples/beginner/upload-files/main.go
Normal file
70
_examples/beginner/upload-files/main.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.AttachView(view.HTML("./templates", ".html"))
|
||||
|
||||
// Serve the form.html to the user
|
||||
app.Get("/upload", func(ctx context.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.ViewData("", token)
|
||||
ctx.View("upload_form.html")
|
||||
})
|
||||
|
||||
// Handle the post request from the upload_form.html to the server
|
||||
app.Post("/upload", context.LimitRequestBodySize(10<<20),
|
||||
func(ctx context.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.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.HTML("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.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
io.Copy(out, file)
|
||||
})
|
||||
|
||||
// start the server at http://localhost:8080
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
12
_examples/beginner/upload-files/templates/upload_form.html
Normal file
12
_examples/beginner/upload-files/templates/upload_form.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<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>
|
||||
@@ -1,37 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
// User bind struct
|
||||
type User struct {
|
||||
Firstname string `json:"firstname"`
|
||||
Lastname string `json:"lastname"`
|
||||
City string `json:"city"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Post("/decode", func(ctx *iris.Context) {
|
||||
app.Post("/decode", func(ctx context.Context) {
|
||||
var user User
|
||||
ctx.ReadJSON(&user)
|
||||
|
||||
ctx.Writef("%s %s is %d years old!", user.Firstname, user.Lastname, user.Age)
|
||||
ctx.Writef("%s %s is %d years old and comes from %s!", user.Firstname, user.Lastname, user.Age, user.City)
|
||||
})
|
||||
|
||||
app.Get("/encode", func(ctx *iris.Context) {
|
||||
app.Get("/encode", func(ctx context.Context) {
|
||||
peter := User{
|
||||
Firstname: "John",
|
||||
Lastname: "Doe",
|
||||
City: "Neither FBI knows!!!",
|
||||
Age: 25,
|
||||
}
|
||||
|
||||
ctx.JSON(iris.StatusOK, peter)
|
||||
ctx.StatusCode(iris.StatusOK)
|
||||
ctx.JSON(peter)
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user