mirror of
https://github.com/kataras/iris.git
synced 2025-01-23 10:41:03 +01:00
examples: update the cors example to be easier for beginners
And update the pug view engine's vendor jade template engine to yesterday version 1 (tested and worked) to fix https://github.com/kataras/iris/issues/1125 Former-commit-id: 0ea7a8dd97ab13e5ecf984c379234cc671f5d84e
This commit is contained in:
parent
d6964acfcd
commit
22782bbefe
38
_examples/experimental-handlers/cors/simple/client/main.go
Normal file
38
_examples/experimental-handlers/cors/simple/client/main.go
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/kataras/iris"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NOTE: THIS IS OPTIONALLY.
|
||||||
|
// It is just an example of communication between cors/simple/main.go and your app
|
||||||
|
// based on issues that beginners had with it.
|
||||||
|
// You should use your own favourite library for HTTP requests (any programming language ofc).
|
||||||
|
//
|
||||||
|
// Replace the '8fc93b1c.ngrok.io' with a domain which
|
||||||
|
// exposes the cors/simple/main.go server side.
|
||||||
|
const url = "http://8fc93b1c.ngrok.io/api/v1/mailer"
|
||||||
|
|
||||||
|
var clientSide = []byte(`<script type="text/javascript">
|
||||||
|
fetch("` + url + `", {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Access-Control-Allow-Origin": "*"
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
mode: "cors",
|
||||||
|
body: JSON.stringify({ email: "mymail@mail.com" }),
|
||||||
|
});
|
||||||
|
</script>`)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
app := iris.New()
|
||||||
|
app.Get("/", func(ctx iris.Context) {
|
||||||
|
ctx.Write(clientSide)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Start and navigate to http://localhost:8080
|
||||||
|
// and go to the previous terminal of your running cors/simple/main.go server
|
||||||
|
// and see the logs.
|
||||||
|
app.Run(iris.Addr(":8080"))
|
||||||
|
}
|
|
@ -1,23 +1,32 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
// go get -u github.com/iris-contrib/middleware/...
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/kataras/iris"
|
"github.com/kataras/iris"
|
||||||
|
|
||||||
"github.com/iris-contrib/middleware/cors"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
app := iris.New()
|
app := iris.New()
|
||||||
|
|
||||||
crs := cors.New(cors.Options{
|
crs := func(ctx iris.Context) {
|
||||||
AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts.
|
ctx.Header("Access-Control-Allow-Origin", "*")
|
||||||
AllowCredentials: true,
|
ctx.Header("Access-Control-Allow-Credentials", "true")
|
||||||
})
|
ctx.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type")
|
||||||
|
ctx.Next()
|
||||||
|
} // or "github.com/iris-contrib/middleware/cors"
|
||||||
|
|
||||||
v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight.
|
v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight.
|
||||||
{
|
{
|
||||||
|
v1.Post("/mailer", func(ctx iris.Context) {
|
||||||
|
var any iris.Map
|
||||||
|
err := ctx.ReadJSON(&any)
|
||||||
|
if err != nil {
|
||||||
|
ctx.WriteString(err.Error())
|
||||||
|
ctx.StatusCode(iris.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx.Application().Logger().Infof("received %#+v", any)
|
||||||
|
})
|
||||||
|
|
||||||
v1.Get("/home", func(ctx iris.Context) {
|
v1.Get("/home", func(ctx iris.Context) {
|
||||||
ctx.WriteString("Hello from /home")
|
ctx.WriteString("Hello from /home")
|
||||||
})
|
})
|
||||||
|
@ -35,5 +44,5 @@ func main() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
app.Run(iris.Addr("localhost:8080"))
|
app.Run(iris.Addr(":80"))
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,134 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/kataras/iris"
|
||||||
|
"github.com/kataras/iris/middleware/logger"
|
||||||
|
|
||||||
|
"github.com/kataras/golog"
|
||||||
|
)
|
||||||
|
|
||||||
|
const deleteFileOnExit = false
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
app := iris.New()
|
||||||
|
|
||||||
|
logFile := newLogFile()
|
||||||
|
defer func() {
|
||||||
|
logFile.Close()
|
||||||
|
if deleteFileOnExit {
|
||||||
|
os.Remove(logFile.Name())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Handle the logs by yourself using the `app.Logger#Handle` method.
|
||||||
|
// Return true if that handled, otherwise will print to the screen.
|
||||||
|
// You can also use the `app.Logger#SetOutput/AddOutput` to change or add
|
||||||
|
// multi (io.Writer) outputs if you just want to print the message
|
||||||
|
// somewhere else than the terminal screen.
|
||||||
|
app.Logger().Handle(func(l *golog.Log) bool {
|
||||||
|
_, fn, line, _ := runtime.Caller(5)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// formatted date string based on the `golog#TimeFormat`, which can be customized.
|
||||||
|
// Or use the golog.Log#Time field to get the exact time.Time instance.
|
||||||
|
datetime = l.FormatTime()
|
||||||
|
// the log's message level.
|
||||||
|
level = golog.GetTextForLevel(l.Level, false)
|
||||||
|
// the log's message.
|
||||||
|
message = l.Message
|
||||||
|
// the source code line of where it is called,
|
||||||
|
// this can differ on your app, see runtime.Caller(%d).
|
||||||
|
source = fmt.Sprintf("%s#%d", fn, line)
|
||||||
|
)
|
||||||
|
|
||||||
|
// You can always use a custom json structure and json.Marshal and logFile.Write(its result)
|
||||||
|
// but it is faster to just build your JSON string by yourself as we do below.
|
||||||
|
jsonStr := fmt.Sprintf(`{"datetime":"%s","level":"%s","message":"%s","source":"%s"}`, datetime, level, message, source)
|
||||||
|
fmt.Fprintln(logFile, jsonStr)
|
||||||
|
|
||||||
|
/* Example output:
|
||||||
|
{"datetime":"2018/10/31 13:13","level":"[INFO]","message":"My server started","source":"c:/mygopath/src/github.com/kataras/iris/_examples/http_request/request-logger/request-logger-file-json/main.go#71"}
|
||||||
|
*/
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
r := newRequestLogger()
|
||||||
|
|
||||||
|
app.Use(r)
|
||||||
|
app.OnAnyErrorCode(r, func(ctx iris.Context) {
|
||||||
|
ctx.HTML("<h1> Error: Please try <a href ='/'> this </a> instead.</h1>")
|
||||||
|
})
|
||||||
|
|
||||||
|
h := func(ctx iris.Context) {
|
||||||
|
ctx.Writef("Hello from %s", ctx.Path())
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Get("/", h)
|
||||||
|
|
||||||
|
app.Get("/1", h)
|
||||||
|
|
||||||
|
app.Get("/2", h)
|
||||||
|
|
||||||
|
app.Logger().Info("My server started")
|
||||||
|
// http://localhost:8080
|
||||||
|
// http://localhost:8080/1
|
||||||
|
// http://localhost:8080/2
|
||||||
|
// http://lcoalhost:8080/notfoundhere
|
||||||
|
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
|
||||||
|
}
|
||||||
|
|
||||||
|
var excludeExtensions = [...]string{
|
||||||
|
".js",
|
||||||
|
".css",
|
||||||
|
".jpg",
|
||||||
|
".png",
|
||||||
|
".ico",
|
||||||
|
".svg",
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRequestLogger() iris.Handler {
|
||||||
|
c := logger.Config{
|
||||||
|
Status: true,
|
||||||
|
IP: true,
|
||||||
|
Method: true,
|
||||||
|
Path: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// we don't want to use the logger
|
||||||
|
// to log requests to assets and etc
|
||||||
|
c.AddSkipper(func(ctx iris.Context) bool {
|
||||||
|
path := ctx.Path()
|
||||||
|
for _, ext := range excludeExtensions {
|
||||||
|
if strings.HasSuffix(path, ext) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
|
||||||
|
return logger.New(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// get a filename based on the date, file logs works that way the most times
|
||||||
|
// but these are just a sugar.
|
||||||
|
func todayFilename() string {
|
||||||
|
today := time.Now().Format("Jan 02 2006")
|
||||||
|
return today + ".json"
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
return f
|
||||||
|
}
|
4
go.mod
4
go.mod
|
@ -3,7 +3,7 @@ module github.com/kataras/iris
|
||||||
require (
|
require (
|
||||||
github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7 // indirect
|
github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7 // indirect
|
||||||
github.com/BurntSushi/toml v0.3.1
|
github.com/BurntSushi/toml v0.3.1
|
||||||
github.com/Joker/jade v0.7.0
|
github.com/Joker/jade v1.0.0
|
||||||
github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc
|
github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc
|
||||||
github.com/ajg/form v0.0.0-20160822230020-523a5da1a92f // indirect
|
github.com/ajg/form v0.0.0-20160822230020-523a5da1a92f // indirect
|
||||||
github.com/aymerick/raymond v2.0.2+incompatible
|
github.com/aymerick/raymond v2.0.2+incompatible
|
||||||
|
@ -59,7 +59,7 @@ require (
|
||||||
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
|
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
|
||||||
github.com/yudai/pp v2.0.1+incompatible // indirect
|
github.com/yudai/pp v2.0.1+incompatible // indirect
|
||||||
golang.org/x/crypto v0.0.0-20180927165925-5295e8364332
|
golang.org/x/crypto v0.0.0-20180927165925-5295e8364332
|
||||||
golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3 // indirect
|
golang.org/x/net v0.0.0-20181102091132-c10e9556a7bc // indirect
|
||||||
golang.org/x/sys v0.0.0-20180928133829-e4b3c5e90611 // indirect
|
golang.org/x/sys v0.0.0-20180928133829-e4b3c5e90611 // indirect
|
||||||
gopkg.in/ini.v1 v1.38.3 // indirect
|
gopkg.in/ini.v1 v1.38.3 // indirect
|
||||||
gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce // indirect
|
gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce // indirect
|
||||||
|
|
7
go.sum
7
go.sum
|
@ -2,8 +2,8 @@ github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7 h1:PqzgE6kAMi
|
||||||
github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8=
|
github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8=
|
||||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||||
github.com/Joker/jade v0.7.0 h1:9sEpF/GAfkn0D0n+x8/SVGpxvdjIStsyPaTvtXW6z/U=
|
github.com/Joker/jade v1.0.0 h1:lOCEPvTAtWfLpSZYMOv/g44MGQFAolbKh2khHHGu0Kc=
|
||||||
github.com/Joker/jade v0.7.0/go.mod h1:R1kvvouJogE6SnKqO5Qw3j2rCE2T9HjIWaFeSET/qMQ=
|
github.com/Joker/jade v1.0.0/go.mod h1:efZIdO0py/LtcJRSa/j2WEklMSAw84WV0zZVMxNToB8=
|
||||||
github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc h1:zZYkIbeMNcH1lhztdVxy4+Ykk8NoMhqUfSigsrT/x7Y=
|
github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc h1:zZYkIbeMNcH1lhztdVxy4+Ykk8NoMhqUfSigsrT/x7Y=
|
||||||
github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0=
|
github.com/Shopify/goreferrer v0.0.0-20180807163728-b9777dc9f9cc/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0=
|
||||||
github.com/ajg/form v0.0.0-20160822230020-523a5da1a92f h1:zvClvFQwU++UpIUBGC8YmDlfhUrweEy1R1Fj1gu5iIM=
|
github.com/ajg/form v0.0.0-20160822230020-523a5da1a92f h1:zvClvFQwU++UpIUBGC8YmDlfhUrweEy1R1Fj1gu5iIM=
|
||||||
|
@ -125,6 +125,9 @@ golang.org/x/crypto v0.0.0-20180927165925-5295e8364332/go.mod h1:6SG95UA2DQfeDnf
|
||||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3 h1:dgd4x4kJt7G4k4m93AYLzM8Ni6h2qLTfh9n9vXJT3/0=
|
golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3 h1:dgd4x4kJt7G4k4m93AYLzM8Ni6h2qLTfh9n9vXJT3/0=
|
||||||
golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20181102091132-c10e9556a7bc h1:ZMCWScCvS2fUVFw8LOpxyUUW5qiviqr4Dg5NdjLeiLU=
|
||||||
|
golang.org/x/net v0.0.0-20181102091132-c10e9556a7bc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
|
||||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
|
|
@ -32,7 +32,7 @@ type (
|
||||||
funcs map[string]interface{}
|
funcs map[string]interface{}
|
||||||
|
|
||||||
//
|
//
|
||||||
middleware func(name string, contents string) (string, error)
|
middleware func(name string, contents []byte) (string, error)
|
||||||
Templates *template.Template
|
Templates *template.Template
|
||||||
//
|
//
|
||||||
}
|
}
|
||||||
|
@ -266,7 +266,7 @@ func (s *HTMLEngine) loadDirectory() error {
|
||||||
tmpl := s.Templates.New(name)
|
tmpl := s.Templates.New(name)
|
||||||
tmpl.Option(s.options...)
|
tmpl.Option(s.options...)
|
||||||
if s.middleware != nil {
|
if s.middleware != nil {
|
||||||
contents, err = s.middleware(name, contents)
|
contents, err = s.middleware(name, buf)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
templateErr = err
|
templateErr = err
|
||||||
|
@ -364,7 +364,7 @@ func (s *HTMLEngine) loadAssets() error {
|
||||||
tmpl.Option(s.options...)
|
tmpl.Option(s.options...)
|
||||||
|
|
||||||
if s.middleware != nil {
|
if s.middleware != nil {
|
||||||
contents, err = s.middleware(name, contents)
|
contents, err = s.middleware(name, buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
templateErr = fmt.Errorf("%v for name '%s'", err, name)
|
templateErr = fmt.Errorf("%v for name '%s'", err, name)
|
||||||
continue
|
continue
|
||||||
|
|
|
@ -235,7 +235,7 @@ type (
|
||||||
broadcast Emitter // pre-defined emitter that sends message to all except this
|
broadcast Emitter // pre-defined emitter that sends message to all except this
|
||||||
all Emitter // pre-defined emitter which sends message to all clients
|
all Emitter // pre-defined emitter which sends message to all clients
|
||||||
|
|
||||||
// access to the Context, use with causion, you can't use response writer as you imagine.
|
// access to the Context, use with caution, you can't use response writer as you imagine.
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
values ConnectionValues
|
values ConnectionValues
|
||||||
server *Server
|
server *Server
|
||||||
|
|
Loading…
Reference in New Issue
Block a user