Permalink
Browse files

Update examples

  • Loading branch information...
kataras committed Jul 18, 2018
1 parent bf4c79d commit e7595e4c7e186ab70b52687cbb7415a3c56eebc1
Showing with 1,445 additions and 624 deletions.
  1. +1 −1 LICENSE
  2. +6 −0 README.md
  3. +64 −0 cookies/basic/main.go
  4. +32 −0 cookies/basic/main_test.go
  5. +59 −0 cookies/securecookie/main.go
  6. +34 −0 cookies/securecookie/main_test.go
  7. +2 −2 experimental-handlers/csrf/views/user/signup.html
  8. +3 −3 file-server/favicon/main.go
  9. +5 −10 http_request/request-logger/main.go
  10. +1 −1 http_request/request-logger/request-logger-file/main.go
  11. +67 −11 http_request/upload-file/main.go
  12. +9 −6 http_request/upload-file/templates/upload_form.html
  13. +1 −1 http_responsewriter/README.md
  14. +5 −0 mvc/login/main.go
  15. +72 −0 mvc/middleware/without-ctx-next/main.go
  16. +325 −55 routing/README.md
  17. +10 −10 sessions/README.md
  18. +6 −3 sessions/database/badger/main.go
  19. +3 −2 sessions/database/boltdb/main.go
  20. +50 −6 sessions/database/redis/main.go
  21. +1 −1 sessions/flash-messages/main.go
  22. +1 −1 sessions/overview/main.go
  23. +4 −3 sessions/securecookie/main.go
  24. +7 −0 sessions/standalone/main.go
  25. +3 −3 tutorial/caddy/README.md
  26. +4 −2 tutorial/url-shortener/factory.go
  27. +1 −1 tutorial/url-shortener/main.go
  28. +0 −20 vendor/github.com/satori/go.uuid/LICENSE
  29. +0 −481 vendor/github.com/satori/go.uuid/uuid.go
  30. +29 −0 view/template_pug_0/main.go
  31. +25 −0 view/template_pug_0/templates/index.pug
  32. +42 −0 view/template_pug_1/main.go
  33. +20 −0 view/template_pug_1/templates/index.pug
  34. +28 −0 view/template_pug_2/main.go
  35. +2 −0 view/template_pug_2/templates/footer.pug
  36. +4 −0 view/template_pug_2/templates/header.pug
  37. +7 −0 view/template_pug_2/templates/index.pug
  38. +20 −0 view/template_pug_3/main.go
  39. +7 −0 view/template_pug_3/templates/index.pug
  40. +7 −0 view/template_pug_3/templates/layout.pug
  41. +412 −0 webassembly/basic/client/go-wasm-runtime.js
  42. +10 −0 webassembly/basic/client/hello.html
  43. +15 −0 webassembly/basic/client/hello_go11beta1.go
  44. +13 −0 webassembly/basic/client/main.js
  45. +27 −0 webassembly/basic/main.go
  46. +1 −1 websocket/README.md
@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2016-2017 Gerasimos Maropoulos and contributors.
Copyright (c) 2016-2018 Gerasimos Maropoulos and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -14,6 +14,7 @@ It doesn't contain "best ways" neither explains all its features. It's just a si
* [Overview](overview)
* [Hello world!](hello-world/main.go)
* [Hello WebAssemply!](webassembly/basic/main.go) **NEW**
* [Glimpse](overview/main.go)
* [Tutorial: Online Visitors](tutorial/online-visitors/main.go)
* [Tutorial: URL Shortener using BoltDB](tutorial/url-shortener/main.go)
@@ -82,6 +83,11 @@ It doesn't contain "best ways" neither explains all its features. It's just a si
* [The `url` tmpl func](view/template_html_4/main.go)
* [Inject Data Between Handlers](view/context-view-data/main.go)
* [Embedding Templates Into App Executable File](view/embedding-templates-into-app/main.go)
* [Write to a custom `io.Writer`](view/write-to/main.go)
* [Greeting with Pug (Jade)`](view/template_pug_0/main.go)
* [Pug (Jade) Actions`](view/template_pug_1/main.go)
* [Pug (Jade) Includes`](view/template_pug_2/main.go)
* [Pug (Jade) Extends`](view/template_pug_3/main.go)
* [Authentication](authentication)
* [Basic Authentication](authentication/basicauth/main.go)
* [OAUth2](authentication/oauth2/main.go)
@@ -0,0 +1,64 @@
package main
import "github.com/kataras/iris"
func newApp() *iris.Application {
app := iris.New()
// Set A Cookie.
app.Get("/cookies/{name}/{value}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
value := ctx.Params().Get("value")
ctx.SetCookieKV(name, value) // <--
// Alternatively: ctx.SetCookie(&http.Cookie{...})
//
// If you want to set custom the path:
// ctx.SetCookieKV(name, value, iris.CookiePath("/custom/path/cookie/will/be/stored"))
//
// If you want to be visible only to current request path:
// (note that client should be responsible for that if server sent an empty cookie's path, all browsers are compatible)
// ctx.SetCookieKV(name, value, iris.CookieCleanPath /* or iris.CookiePath("") */)
// More:
// iris.CookieExpires(time.Duration)
// iris.CookieHTTPOnly(false)
ctx.Writef("cookie added: %s = %s", name, value)
})
// Retrieve A Cookie.
app.Get("/cookies/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
value := ctx.GetCookie(name) // <--
// If you want more than the value then:
// cookie, err := ctx.Request().Cookie(name)
// if err != nil {
// handle error.
// }
ctx.WriteString(value)
})
// Delete A Cookie.
app.Delete("/cookies/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
ctx.RemoveCookie(name) // <--
// If you want to set custom the path:
// ctx.SetCookieKV(name, value, iris.CookiePath("/custom/path/cookie/will/be/stored"))
ctx.Writef("cookie %s removed", name)
})
return app
}
func main() {
app := newApp()
// GET: http://localhost:8080/cookies/my_name/my_value
// GET: http://localhost:8080/cookies/my_name
// DELETE: http://localhost:8080/cookies/my_name
app.Run(iris.Addr(":8080"))
}
@@ -0,0 +1,32 @@
package main
import (
"fmt"
"testing"
"github.com/kataras/iris/httptest"
)
func TestCookiesBasic(t *testing.T) {
app := newApp()
e := httptest.New(t, app, httptest.URL("http://example.com"))
cookieName, cookieValue := "my_cookie_name", "my_cookie_value"
// Test Set A Cookie.
t1 := e.GET(fmt.Sprintf("/cookies/%s/%s", cookieName, cookieValue)).Expect().Status(httptest.StatusOK)
t1.Cookie(cookieName).Value().Equal(cookieValue) // validate cookie's existence, it should be there now.
t1.Body().Contains(cookieValue)
// Test Retrieve A Cookie.
t2 := e.GET(fmt.Sprintf("/cookies/%s", cookieName)).Expect().Status(httptest.StatusOK)
t2.Body().Equal(cookieValue)
// Test Remove A Cookie.
t3 := e.DELETE(fmt.Sprintf("/cookies/%s", cookieName)).Expect().Status(httptest.StatusOK)
t3.Body().Contains(cookieName)
t4 := e.GET(fmt.Sprintf("/cookies/%s", cookieName)).Expect().Status(httptest.StatusOK)
t4.Cookies().Empty()
t4.Body().Empty()
}
@@ -0,0 +1,59 @@
package main
// developers can use any library to add a custom cookie encoder/decoder.
// At this example we use the gorilla's securecookie package:
// $ go get github.com/gorilla/securecookie
// $ go run main.go
import (
"github.com/kataras/iris"
"github.com/gorilla/securecookie"
)
var (
// AES only supports key sizes of 16, 24 or 32 bytes.
// You either need to provide exactly that amount or you derive the key from what you type in.
hashKey = []byte("the-big-and-secret-fash-key-here")
blockKey = []byte("lot-secret-of-characters-big-too")
sc = securecookie.New(hashKey, blockKey)
)
func newApp() *iris.Application {
app := iris.New()
// Set A Cookie.
app.Get("/cookies/{name}/{value}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
value := ctx.Params().Get("value")
ctx.SetCookieKV(name, value, iris.CookieEncode(sc.Encode)) // <--
ctx.Writef("cookie added: %s = %s", name, value)
})
// Retrieve A Cookie.
app.Get("/cookies/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
value := ctx.GetCookie(name, iris.CookieDecode(sc.Decode)) // <--
ctx.WriteString(value)
})
// Delete A Cookie.
app.Delete("/cookies/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
ctx.RemoveCookie(name) // <--
ctx.Writef("cookie %s removed", name)
})
return app
}
func main() {
app := newApp()
app.Run(iris.Addr(":8080"))
}
@@ -0,0 +1,34 @@
package main
import (
"fmt"
"testing"
"github.com/kataras/iris/httptest"
)
func TestCookiesBasic(t *testing.T) {
app := newApp()
e := httptest.New(t, app, httptest.URL("http://example.com"))
cookieName, cookieValue := "my_cookie_name", "my_cookie_value"
// Test Set A Cookie.
t1 := e.GET(fmt.Sprintf("/cookies/%s/%s", cookieName, cookieValue)).Expect().Status(httptest.StatusOK)
// note that this will not work because it doesn't always returns the same value:
// cookieValueEncoded, _ := sc.Encode(cookieName, cookieValue)
t1.Cookie(cookieName).Value().NotEqual(cookieValue) // validate cookie's existence and value is not on its raw form.
t1.Body().Contains(cookieValue)
// Test Retrieve A Cookie.
t2 := e.GET(fmt.Sprintf("/cookies/%s", cookieName)).Expect().Status(httptest.StatusOK)
t2.Body().Equal(cookieValue)
// Test Remove A Cookie.
t3 := e.DELETE(fmt.Sprintf("/cookies/%s", cookieName)).Expect().Status(httptest.StatusOK)
t3.Body().Contains(cookieName)
t4 := e.GET(fmt.Sprintf("/cookies/%s", cookieName)).Expect().Status(httptest.StatusOK)
t4.Cookies().Empty()
t4.Body().Empty()
}
@@ -1,4 +1,4 @@
<form method="POST" action="/user/signup">
{{ .csrfField }}
<button type="submit">Procceed</button>
</form>
<button type="submit">Proceed</button>
</form>
@@ -8,10 +8,10 @@ func main() {
app := iris.New()
// This will serve the ./static/favicons/favicon.ico to: localhost:8080/favicon.ico
app.Favicon("./static/favicons/favicon.ico.ico")
app.Favicon("./static/favicons/favicon.ico")
// app.Favicon("./static/favicons/favicon.ico.ico", "/favicon_16_16.ico")
// This will serve the ./static/favicons/favicon.ico.ico to: localhost:8080/favicon_16_16.ico
// app.Favicon("./static/favicons/favicon.\\.ico", "/favicon_16_16.ico")
// This will serve the ./static/favicons/favicon.ico to: localhost:8080/favicon_16_16.ico
app.Get("/", func(ctx iris.Context) {
ctx.HTML(`<a href="/favicon.ico"> press here to see the favicon.ico</a>.
@@ -17,22 +17,17 @@ func main() {
Method: true,
// Path displays the request path
Path: true,
// Query appends the url query to the Path.
Query: true,
//Columns: true,
// if !empty then its contents derives from `ctx.Values().Get("logger_message")
// will be added to the logs.
MessageContextKeys: []string{"logger_message"},
// MessageHeaderKeys if not empty,
// the middleware will try to fetch
// the contents with `ctx.Values().Get(MessageHeaderKey)`
// and if available then these contents will be
// appended as part of the logs (with `%v`, in order to be able to set a struct too),
// if Columns field was setted to true then
// a new column will be added named 'HeaderMessage'.
//
// Defaults to empty.
// MessageHeaderKeys: []string{},
// if !empty then its contents derives from `ctx.GetHeader("User-Agent")
MessageHeaderKeys: []string{"User-Agent"},
})
app.Use(customLogger)
@@ -85,7 +85,7 @@ func newRequestLogger() (h iris.Handler, close func() error) {
return err
}
c.LogFunc = func(now time.Time, latency time.Duration, status, ip, method, path string, message, headerMessage interface{}) {
c.LogFunc = func(now time.Time, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) {
output := logger.Columnize(now.Format("2006/01/02 - 15:04:05"), latency, status, ip, method, path, message, headerMessage)
logFile.Write([]byte(output))
}
@@ -11,6 +11,8 @@ import (
"github.com/kataras/iris"
)
const maxSize = 5 << 20 // 5MB
func main() {
app := iris.New()
@@ -32,18 +34,72 @@ func main() {
ctx.View("upload_form.html", token)
})
// Handle the post request from the upload_form.html to the server
app.Post("/upload", func(ctx iris.Context) {
// iris.LimitRequestBodySize(32 <<20) as middleware to a route
// or use ctx.SetMaxRequestBodySize(32 << 20)
// to limit the whole request body size,
//
// or let the configuration option at app.Run for global setting
// for POST/PUT methods, including uploads of course.
/* Read before continue.
// Get the file from the request.
0. The default post max size is 32MB,
you can extend it to read more data using the `iris.WithPostMaxMemory(maxSize)` configurator at `app.Run`,
note that this will not be enough for your needs, read below.
1. The faster way to check the size is using the `ctx.GetContentLength()` which returns the whole request's size
(plus a logical number like 2MB or even 10MB for the rest of the size like headers). You can create a
middleware to adapt this to any necessary handler.
myLimiter := func(ctx iris.Context) {
if ctx.GetContentLength() > maxSize { // + 2 << 20 {
ctx.StatusCode(iris.StatusRequestEntityTooLarge)
return
}
ctx.Next()
}
app.Post("/upload", myLimiter, myUploadHandler)
Most clients will set the "Content-Length" header (like browsers) but it's always better to make sure that any client
can't send data that your server can't or doesn't want to handle. This can be happen using
the `app.Use(LimitRequestBodySize(maxSize))` (as app or route middleware)
or the `ctx.SetMaxRequestBodySize(maxSize)` to limit the request based on a customized logic inside a particular handler, they're the same,
read below.
2. You can force-limit the request body size inside a handler using the `ctx.SetMaxRequestBodySize(maxSize)`,
this will force the connection to close if the incoming data are larger (most clients will receive it as "connection reset"),
use that to make sure that the client will not send data that your server can't or doesn't want to accept, as a fallback.
app.Post("/upload", iris.LimitRequestBodySize(maxSize), myUploadHandler)
OR
app.Post("/upload", func(ctx iris.Context){
ctx.SetMaxRequestBodySize(maxSize)
// [...]
})
3. Another way is to receive the data and check the second return value's `Size` value of the `ctx.FormFile`, i.e `info.Size`, this will give you
the exact file size, not the whole incoming request data length.
app.Post("/", func(ctx iris.Context){
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()
if info.Size > maxSize {
ctx.StatusCode(iris.StatusRequestEntityTooLarge)
return
}
// [...]
})
*/
// Handle the post request from the upload_form.html to the server
app.Post("/upload", iris.LimitRequestBodySize(maxSize+1<<20), func(ctx iris.Context) {
// 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>")
@@ -68,6 +124,6 @@ func main() {
io.Copy(out, file)
})
// start the server at http://localhost:8080 with post limit at 32 MB.
app.Run(iris.Addr(":8080"), iris.WithPostMaxMemory(32<<20))
// start the server at http://localhost:8080 with post limit at 5 MB.
app.Run(iris.Addr(":8080") /* 0.*/, iris.WithPostMaxMemory(maxSize))
}
Oops, something went wrong.

0 comments on commit e7595e4

Please sign in to comment.