1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-09 13:05:56 +00: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:
Gerasimos (Makis) Maropoulos
2018-11-06 04:06:50 +02:00
parent d6964acfcd
commit 22782bbefe
7 changed files with 201 additions and 17 deletions

View 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"))
}

View File

@@ -1,23 +1,32 @@
package main
// go get -u github.com/iris-contrib/middleware/...
import (
"github.com/kataras/iris"
"github.com/iris-contrib/middleware/cors"
)
func main() {
app := iris.New()
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts.
AllowCredentials: true,
})
crs := func(ctx iris.Context) {
ctx.Header("Access-Control-Allow-Origin", "*")
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.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) {
ctx.WriteString("Hello from /home")
})
@@ -35,5 +44,5 @@ func main() {
})
}
app.Run(iris.Addr("localhost:8080"))
app.Run(iris.Addr(":80"))
}

View File

@@ -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
}