Coder Social home page Coder Social logo

kataras / iris Goto Github PK

View Code? Open in Web Editor NEW
24.9K 690.0 2.5K 17.2 MB

The fastest HTTP/2 Go Web Framework. New, modern and easy to learn. Fast development with Code you control. Unbeatable cost-performance ratio :rocket:

Home Page: https://www.iris-go.com

License: BSD 3-Clause "New" or "Revised" License

Go 93.68% HTML 2.14% Pug 0.04% Dockerfile 0.09% JavaScript 3.50% CSS 0.55%
go iris web-framework mvc golang dependency-injection http2 sessions websocket

iris's Introduction

Iris Web Framework

build status view examples chat donate

Iris is a fast, simple yet fully featured and very efficient web framework for Go.

It provides a beautifully expressive and easy to use foundation for your next website or API.

Learn what others saying about Iris and star this open-source project to support its potentials.

Benchmarks: Jul 18, 2020 at 10:46am (UTC)

package main

import "github.com/kataras/iris/v12"

func main() {
  app := iris.New()
  app.Use(iris.Compression)

  app.Get("/", func(ctx iris.Context) {
    ctx.HTML("Hello <strong>%s</strong>!", "World")
  })

  app.Listen(":8080")
}

As one Go developer once said, Iris got you covered all-round and standing strong over the years.

Some of the features Iris offers:

  • HTTP/2 (Push, even Embedded data)
  • Middleware (Accesslog, Basicauth, CORS, gRPC, Anti-Bot hCaptcha, JWT, MethodOverride, ModRevision, Monitor, PPROF, Ratelimit, Anti-Bot reCaptcha, Recovery, RequestID, Rewrite)
  • API Versioning
  • Model-View-Controller
  • Websockets
  • gRPC
  • Auto-HTTPS
  • Builtin support for ngrok to put your app on the internet, the fastest way
  • Unique Router with dynamic path as parameter with standard types like :uuid, :string, :int... and the ability to create your own
  • Compression
  • View Engines (HTML, Django, Handlebars, Pug/Jade and more)
  • Create your own File Server and host your own WebDAV server
  • Cache
  • Localization (i18n, sitemap)
  • Sessions
  • Rich Responses (HTML, Text, Markdown, XML, YAML, Binary, JSON, JSONP, Protocol Buffers, MessagePack, Content Negotiation, Streaming, Server-Sent Events and more)
  • Response Compression (gzip, deflate, brotli, snappy, s2)
  • Rich Requests (Bind URL Query, Headers, Form, Text, XML, YAML, Binary, JSON, Validation, Protocol Buffers, MessagePack and more)
  • Dependency Injection (MVC, Handlers, API Routers)
  • Testing Suite
  • And the most important... you get fast answers and support from the 1st day until now - that's six full years!

πŸ‘‘ Supporters

With your help, we can improve Open Source web development for everyone!

getsentry github lensesio thepunterbot tstangenberg cuong48d rubyangxg draFWM gf3 trading-peter AlbinoGeek basilarchia sumjoe simpleittools xiaozhuai Remydeme celsosz linxcoder jnelle TechMaster janwebdev altafino jakoubek alekperos day0ng hengestone thomasfr CetinBasoz International Juanses SometimesMage ansrivas ekobayong lexrus li3p madhu72 se77en vincent-li sascha11110 clichi2002 derReineke Sirisap22 primadi agoncecelia antonio-pedrazzini chrisliang12 zyu hobysmith clacroix njeff3 ixalender mubariz-ahmed Cesar DavidShaw th31nitiate stgrosshh rodrigoghm Didainius DmarshalTU IwateKyle Little-YangYang Major2828 MatejLach amritpal042 andrefiorot boomhut coderperu cshum dtrifonov geordee guanting112 iantuan ichenhe angelaahhu anhxuanpham annieruci antoniejiao artman328 b2cbd baoch254 icibiri jewe11er jfloresremar jingtianfeng kilarusravankumar leandrobraga lfbos lpintes macropas marcmmx mark2b miguel-devs mihado mmckeen75 narven odas0r olaf-lexemo pitexplore pr123 rsousacode sankethpb saz59 shadowfiga siriushaha bastengao skurtz97 srinivasganti syrm tuhao1020 wahyuief xvalen xytis ElNovi IpastorSan KKP4 Lernakow ernestocolombo francisstephan pixelheresy rcapraro beytullahakyuz bjoroen blackHoleNgc1277 bunnycodego carlos-enginner soiestad thanasolykos ukitzmann DanielKirkwood aprinslo1 colinf kyoukhana spazzymoto victorgrey ArishSultan ehayun chrismalek civicwar cnzhangquan danlanxiaohei dfaugusto dkzhang dloprodu donam-givita dph0899 ec0629 edwindna2 ekofedriyanto eli-yip eljefedelrodeodeljefe fenriz07 ffelipelimao frenchmajesty gastropulgite geGao123 globalflea gloudx gnosthi goten002 guanzi008 kukaki oshirokazuhide t6tg 15189573255 AnatolyUA AwsIT BlackHole1 FernandoLangOFC Flammable-Duck Hongjian0619 JoeD Jude-X Kartoffelbot KevinZhouRafael KrishManohar Laotanling Longf99999 Lyansun MihaiPopescu1985 Mohammed8960 NA Neulhan NguyenPhuoc Oka00 PaddyFrenchman RainerGevers Ramblestsad SamuelNeves Scorpio69t Serissa4000 TianJIANG Ubun1 XinYoungCN YukinaMochizuki a112121788 acdias aeonsthorn agent3bood alessandromarotta algoflows hdezoscar93 hieungm hieunmg homerious CSRaghunandan hzxd iuliancarnaru iysaleh jackptoke jackysywk jeff2go jeremiahyan joelywz kamolcu kana99 kattaprasanth keeio GeorgeFourikis keymanye khasanovrs kkdaypenny knavels kohakuhubo korowiov kostasvk lafayetteDan leki75 L-M-Sherlock claudemuller edsongley lemuelroberto liheyuan lingyingtan linuxluigi lipatti maikelcoke marek-kuticka marman-hp mattbowen maxgozou mizzlespot mnievesco mo3lyana motogo mtrense mukunhao mulyawansentosa evan grassshrimp nasoma ngseiyu nikharsaxena nronzel onlysumitg ozfive paulxu21 pesquive petros9282 phil535 pitt134 qiepeipei qiuzhanghua rapita rbondi relaera remopavithran rfunix rhernandez-itemsoft rikoriswandha hazmi-e205 jtgoral ky2s lauweliam risallaw robivictor rubiagatra rxrw saleebm sbenimeli sebyno seun-otosho solohiroshi su1gen sukiejosh svirmi terjelafton thiennguyen93 unixedia vadgun valsorym vguhesan vpiduri vrocadev vuhoanglam walter-wang wixregiga xPoppa yesudeep ymonk yonson2 yusong-offx zhenggangpku SergeShin - BelmonduS Diewald cty4ka martinjanda martinlindhe mdamschen netbaalzovf oliverjosefzimmer talebisinan valkuere lfaynman ArturWierzbicki Supersherm5 aaxx crashCoder derekslenk dochoaj evillgenius75 gog200921 mauricedcastro mwiater sj671 statik supersherm5 thejones letmestudy mblandr midhubalan ndimorle rosales-stephanie shyyawn vcruzato wangbl11 wofka72 yoru74 xsokev oleang michalsz michaelsmanley Curtman SridarDhandapani opusmagna ShahramMebashar b4zz4r bobmcallan fangli galois-tnp geoshan juanxme nguyentamvinhlong pomland-94 tejzpr theantichris tuxaanand raphael-brand willypuzzle malcolm-white-dti HieuLsw carlosmoran092 yangxianglong

πŸ“– Learning Iris

Installation

The only requirement is the Go Programming Language.

Create a new project

$ mkdir myapp
$ cd myapp
$ go mod init myapp
$ go get github.com/kataras/iris/v12@latest # or @v12.2.10
Install on existing project
$ cd myapp
$ go get github.com/kataras/iris/v12@latest

Run

$ go mod tidy -compat=1.21 # -compat="1.21" for windows.
$ go run .

Iris contains extensive and thorough documentation making it easy to get started with the framework.

For a more detailed technical documentation you can head over to our godocs. And for executable code you can always visit the ./_examples repository's subdirectory.

Do you like to read while traveling?

Book cover

follow author on twitter

follow Iris web framework on twitter

follow Iris web framework on facebook

You can request a PDF and online access of the Iris E-Book (New Edition, future v12.2.0+) today and be participated in the development of Iris.

πŸ™Œ Contributing

We'd love to see your contribution to the Iris Web Framework! For more information about contributing to the Iris project please check the CONTRIBUTING.md file.

List of all Contributors

πŸ›‘ Security Vulnerabilities

If you discover a security vulnerability within Iris, please send an e-mail to [email protected]. All security vulnerabilities will be promptly addressed.

πŸ“ License

This project is licensed under the BSD 3-clause license, just like the Go project itself.

The project name "Iris" was inspired by the Greek mythology.

iris's People

Contributors

admpub avatar akiraho avatar asood123 avatar benlampson avatar bgaitanc avatar cainiaodj avatar chengyumeng avatar corebreaker avatar dependabot[bot] avatar eleven26 avatar haritsfahreza avatar hiveminded avatar honux avatar itcrow avatar jerson avatar kataras avatar koddr avatar liguoqinjim avatar lrita avatar majidbigdeli avatar speedwheel avatar takahiko-okada avatar tanomin avatar trungdlp-wolffun avatar tuhao1020 avatar winggao avatar wozz avatar yale8848 avatar zaniadeveloper avatar zeno-code avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

iris's Issues

Persisten session after server restart

Hello, glad to see there is a lot of activity and more user are taking part to make Iris better and better.

Now, I am not really sure how to implement this myself, but what would be the easiest way to make a session persistent after server restart? I tried the example with Redis, but the session was destroyed after server restart.

Any ideas how to achieve this?

Mobiles

Is running iris on mobiles and desktops considered plausible ?

The MCV functionality is server side and so the client will refresh each page. But if it's fast enough it can be enough for many apps.

General Shutdown Handler registration is missing

I know we can register a shutdown handler when a HTTP Server is initialized via a Runner or not.
But this way breaks the encapsulation of HTTP layer to make it up on surface.

We can use Host Supervisors but they a created when servers starts. Shutdown handler can't be registered in middlewares. Plus, for registering that from middleware, we must use a closure variable or global variable, that's give a great complexity in developer code.

With a new method on Application instance to delay shutdown registration and let Iris use it's initialization mechanism.

About proxy

How can i make that my path (for example "localhost/some/api") will be processed by another go service?

File based session storage

Hi, I see "iris" is back up with v8.x . Congratulation to team and @hiveminded

Does Iris / get-ion supports file based session ? Memory based session and database sessions are not optimal requirement for scaling up.

If it's not already there, is it hard to implement them ? Please share some light so that , i can try implementing them.

Thanks

Reference: get-ion/issues-v1#8

undefined: iris.Context - has iris.Context changed to context.Context?

When registering routes on "iris.Application", I get "iris.Context" errors like ".../main.go:14 undefined: iris.Context" even though "github.com/kataras/iris" has been imported. Changing to import "github.com/kataras/iris/context" and using "context.Context" seems to fix this, but I haven't found any docs that explain this change... Is this just a oversight of refactoring, or am I missing something?

Session: decoding cookie can return empty string, but it thinks that session is active

I used securecookie from Gorilla like in example.
The problem is that the decode function can return error "securecookie: expired timestamp". Securecookie has a max age in its configuration.

Therefore the method decodeCookieValue of type Session returns empty string even if its argument is not empty. Then no new session ID is generated, and an empty session ID is sent to load from database. And also, no new cookie is sent to browser.

It's easy to resolve, i've already identified the problem. We have just to regenerate an ID when decoder return empty string (normally this correspond to an error returned by the underlying decoder).

I'm going to post a PR.

Support multi registrations for custom http errors

The problem

The problem is with app.OnErrorCode(404, ... we can register only one handler, that issue can be solved by wrapping handlers together, it's basic functional way to do it, but then we have second problem

Middleware, the second problem

Today we can add middleware to custom errors by calling them manually inside our custom handler, i.,e func(ctx context.Context){ myErrMiddlewre(ctx); myErrHandler(ctx) }.

The ctx.Next() inside these handlers will not be managed correctly, so wrapping handlers for these kind of things is not a solution for apps who depends on middlewares that are specific registered to error handlers.

Solution

Both issues can be solved by allowing registration of multiple Handlers for a specific http error.
i.e app.OnErrorCode(404, myErrMiddleware, myErrHandler) , the ctx.Next() will be respected, so if the myErrMiddleware isn't calling the ctx.Next() then myErrHandler will be not executed, as expected.

Completed

With fe256fe

Logger middleware support for column format and custom log func

The problem

By-default request logger will log to the app.Logger(), if we want to log to a file, we must change the application's logger's output to a file writer, first, i.e app.Logger().Out = *os.File.

This is wrong, the request logger should be easy to use (without any required configuration) but at the same time we must provide functionality that can be adapted without any troubles.

Solution

Therefore, we want to make it easier to adapt a custom log function which will be responsible to log the requests via the request logger, only.

This can be done, simply, by adding a LogFunc to the middleware/logger#Configuration .

New feature

Many developers, including me, like the output to be aligned with columns so a configuration field with something like Columns bool on middleware/logger#Configuration is necessary to control whether to print using columns or print normally, as before.

This Columns should be ignored if LogFunc is not nil, because the LogFunc will receive details, not just the log line (for better customization).

So we will add a Columnize function at the package-level of the request logger middleware, middleware/logger#Columnize which will receive the same arguments as LogFunc does and it will return a column-formatted string which caller can print to the file or anywhere else.

Completed

With fe256fe

redis-database session bug

Hi @kataras , i found that there is another bug in this line:

// ...
storeMaybe, err := db.redis.Get(sid)
if err != nil {
	golog.Errorf("error while trying to load session values(%s) from redis: %v", sid, err)
	return
}

storeDB, ok := storeMaybe.(sessions.RemoteStore) // <- here
if !ok {
	golog.Errorf(`error while trying to load session values(%s) from redis:
	the retrieved value is not a sessions.RemoteStore type, please report that as bug, it should never occur`,sid)
	return
}
// ...

Since the value store of session had already been serialized before setting:

func (db *Database) sync(p sessions.SyncPayload) {
	// ...
	storeB, err := p.Store.Serialize()
	if err != nil {
		golog.Error("error while encoding the remote session store")
		return
	}
        // ...
}

they should be decoded after read from redis:

// bad: storeDB, ok := storeMaybe.(sessions.RemoteStore)
storeDB, err = sessions.DecodeRemoteStore(storeMaybe.([]byte))
if err != nil {
// ...

ReadForm error with nested struct array

Request:

# post form
Items[0].Value=1&Items[1].Value=1

Server:

type S1 struct {
    Items []S2
}
type S2 struct {
    Value string
}

...
obj := &S1{}
err := ctx.ReadForm(obj) //while trying to read formam: not supported type for field "Value" in path "Items[1].Value"
...

work fine with github.com/go-playground/form

Gzip doesn't work for a kind of files

There is a problem with big files or average sized files, for example i tested with jquery non-minified (~ 250 ko).

The code:

package main

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
)

func main() {
	app := iris.New()

	// Put it before the static server, if i put it after, 
	// the response for static files won't be gzipped .
	// We can put it after the static server
	// but only with `app.UseGlobal()`, not `with app.Use()` .
	app.Use(func(ctx context.Context) {
		ctx.Gzip(true)
		ctx.Next()
	})

	// Static server
	app.StaticWeb("/static", "public/common")

	// Starts th serving task
	app.Run(iris.Addr(":8080"))
}

Here the result:
image

The real size of the file:
image

And the response headers in browser:
image

We see that the Content-Length header has the uncompressed size (268039), it should have the compressed size (79470) or the response should be chunked.

Here the response header sent by Django with Gzip Encoding Middleware:
image

I have localized the problem, i'll push a PR soon.

Expiration of the sessions is not restored

I saw that there is a problem when the server restarts. For example if session timeout is set to 30 minutes in session configuration, so the session which will expire in 10 minutes, has not been cleaned after 15 minutes but after 30 minutes, this effect is visible after the server has been restarted.

The cause is the expire date is not restored. The timer task is created from configuration value (30 minutes) instead the remaining time (10 minutes) during the session loading from the database.

can't read sessions on posted page?

package router

import (
	"html/template"
	"irisWeb/models"
	"strconv"
	"time"

	"github.com/go-xorm/xorm"
	"github.com/gorilla/securecookie"

	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
	"github.com/kataras/iris/sessions"
	//SQLITE3
	_ "github.com/mattn/go-sqlite3"
)

const (
	fileDb = "./dbbase/sql3.db"
)

var (
	cookieNameForSessionID = "OneSession"
	hashKey                = []byte("this-is-liujie-password")
	blockKey               = []byte("block-key-with-going-to-be")
	secureCookie           = securecookie.New(hashKey, blockKey)
	mySessions             = sessions.New(sessions.Config{
		Cookie:  cookieNameForSessionID,
		Encode:  secureCookie.Encode,
		Decode:  secureCookie.Decode,
		Expires: time.Hour * 1,
	})
)

//GetIndex Get:/index
func GetIndex(ctx context.Context) {
	session := mySessions.Start(ctx)
	auth, err := session.GetBoolean("authenticated")
	loggerError(ctx, err)

	if !auth {
		ctx.ViewData("yourName", "NOT Authenticated")
		ctx.View("index.html")
		return
	}

	thisUserID := session.GetString("UserId")
	ID, err := strconv.ParseUint(thisUserID, 10, 64)

	loggerError(ctx, err)

	u, err := models.GetUserByUserID(uint(ID))

	loggerError(ctx, err)
	ctx.ViewData("yourName", u.Name)
	ctx.ViewData("imgSrc", template.URL(u.Avatar))

	if err := ctx.View("index.html"); err != nil {
		ctx.StatusCode(iris.StatusInternalServerError)
	}
}

//PostIndex Post:/index from /Authentic/Login
func PostIndex(ctx context.Context) {

	session := mySessions.Start(ctx)
	session.Set("authenticated", false)

	user := models.LoginUser{}

	err := ctx.ReadForm(&user)
	if err != nil {
		ctx.Application().Logger().Error(err.Error())
		ctx.StatusCode(iris.StatusNotFound)
	}

	engine, err := xorm.NewEngine("sqlite3", fileDb)
	loggerError(ctx, err)
	defer engine.Close()

	var requestUser = new(models.UserInfo)

	has, err := engine.Where("name = ? and password = ?", user.Username, user.Password).Get(requestUser)

	loggerError(ctx, err)

	if has {
		session.Set("authenticated", true)
		session.Set("UserId", string(requestUser.ID))

		ctx.ViewData("yourName", requestUser.Name)
		ctx.ViewData("imgSrc", template.URL(requestUser.Avatar))
		ctx.View("index.html")
	} else {
		ctx.StatusCode(403)
	}
}

step 1: get /login
step 2: will redirct /index
step 3: get /index on new page, lost sessions

Register an error handler to all/any http error codes

The problem

If we want to add custom http errors handlers for a specific error handler, we can do that with app.OnErrorCode(statusCode, handler) but if we want to add the same error handler for all or any http errors that user may receive then, today, we have to do it manualy, i.e app.OnErrorCode(401,... app.OnErrorCode(402,... app.OnErrorCode(404,... app.OnErrorCode(500,...` and so on.

The second problem

We could add handlers to all http errors that are >= 400 and <=511 but the web specification doesn't contain all these status codes, for example it doesn't says the error code 419 , so if we add handlers to all of these statuses we may cause problems to developers who may need to add custom error codes to their apps (with Iris we can do it) when specification leaves them unrecognized as official http error status codes.

You can ead more about valid http error codes: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

Solution

We can create an app.OnAnyErrorCode(handlers) which will register the official http error codes (hand-coded to solve the second problem ) by calling the app.OnErrorCode(errCode, handlers...), and we're done, this should be an easy task.

Completed

With fe256fe

MVC: Support for ByByBy... functions without names

Hello and thank you for this nice framework.

Can you please add the Support for GetByBy... functions without names/seperators like GetByItemBy to build URL like /shop/12/98/ and not /shop/12/item/98 ?

Thank you.

[Help]Attach session to Context

Below is my code:

type newContext struct {
context.Context
Session *sessions.Sessions
}

session := sessions.New(sessions.Config{
Cookie: Cookie,
})

app.ContextPool.Attach(func() context.Context {
return &newContext{
Session: session,
Context: context.NewContext(app),
}
})

app.UseGlobal(func(ctx context.Context) {
ctx.Session // <- for example here not working right now ;(
ctx.Next()
})

I have looking through example and overridden Context struct to attach my own context, my question is how can i access session in context something like ctx.Session, or what i'm doing wrong? can someone help me?

Ability to customize Logrus

Logrus is a popular logging package. Some already use this in their projects, and set it up with Console in dev and JSON writers in production. It would be nice to add the ability to customize Logrus inside of Iris. I propose and could easily add the ability to set the Logrus object to use. Even better, would be nice to have it's own context.

go-bindata api changes

The go-bindata package has been updated and now it uses only one function to access the assets when you run go-bindata ./templates/...:

func Asset(name string) ([]byte, error) {
	if f, ok := _bindata[name]; ok {
		return f()
	}
	return nil, fmt.Errorf("Asset %s not found", name)
}

Iris it's using also the AssetNames function which was generated in the past by the old go-bindata API.

These are the two functions that Iris it's using now, one of them has been changed and the other is not present anymore in the file generated file by go-bindata:

// AssetNames returns the names of the assets.
func AssetNames() []string {
	names := make([]string, 0, len(_bindata))
	for name := range _bindata {
		names = append(names, name)
	}
	return names
}

func Asset(name string) ([]byte, error) {
	cannonicalName := strings.Replace(name, "\\", "/", -1)
	if f, ok := _bindata[cannonicalName]; ok {
		a, err := f()
		if err != nil {
			return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err)
		}
		return a.bytes, nil
	}
	return nil, fmt.Errorf("Asset %s not found", name)
}

Can we change the embedding functionality in Iris so we can use the generated file by go-bindata by default?

Not correct host in "Now listening on:" when using iris.Listener

Code for reproduce:

package main

import (

	"github.com/kataras/iris"
	"github.com/valyala/tcplisten"
)

func main() {
	app := iris.New()

	app.Get("/", func(ctx iris.Context) {
		ctx.HTML("<h1>Hello World!</h1>")
	})

	listenerCfg := tcplisten.Config{
		ReusePort:   true,
		DeferAccept: true,
		FastOpen:    true,
	}

	l1, err := listenerCfg.NewListener("tcp4", ":8081")
	if err != nil {
		app.Logger().Fatal(err)
	}

	app.Run(iris.Listener(l1))

}

After run it show next mesage:

Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.

But it isn't correct because program is listen on http://localhost:8081

to fix I use next change in iris listener function:

func Listener(l net.Listener, hostConfigs ...host.Configurator) Runner {
	return func(app *Application) error {
		app.config.vhost = netutil.ResolveVHost(l.Addr().String())
		return app.NewHost(&http.Server{Addr: l.Addr().String()}).
			Configure(hostConfigs...).
			Serve(l)
	}
}

How do i stop update check?

whenever i try to install iris thru dep i pop into this error -->
How do i stop it?

Now listening on: http://localhost:8080
Application started. Press CMD+C to shut down.
[WARN] 2017/09/14 23:27 A new version is available online[8.4.1 > 8.4.0].
Release notes: https://github.com/kataras/iris/blob/master/HISTORY.md#th-07-september-2017--v841
Update now?[y/n]: 
^C%                                                                                                                                                                                        

How can i use template options?

I am try to use option function of html/template
So i try:
tmpl := iris.HTML("./templates", ".html"); tmpl.Option("missingkey=zero"); tmpl.Reload(true);
i got an error:
Option is undefined func
then i try:
tmpl := iris.HTML("./templates", ".html"); tmpl.Templates.Option("missingkey=zero"); tmpl.Reload(true);
i got an error:
tmpl.Templates is nil
So, how can i use html template option?
https://golang.org/pkg/html/template/#Template.Option

Template path issue

Documentation for the iris project can be found at
https://github.com/kataras/iris#-learn.

go version go1.8.3 windows/amd64

File structure
GOPATH
|-src
|---|-myProj
|---|----|-projBase
|---|----|-----|-views
|---|----|-----|----|-index.html
|---|----|-----|-main.go

When run go

go run GOPATH/src/myProj/projBase/main.go

It run properly but it cant get the views html

So i change directory into projBase, then the html is render properly

I found a solution which is not so practical to do so.
_, goDir, _, ok := runtime.Caller(0) if !ok { panic("No caller information") } appDir := path.Dir(goDir) app.RegisterView(iris.HTML(appDir+"/views", ".html").Reload(true))

With the code in main.go and below command, im able to get the views html

go run GOPATH/src/myProj/projBase/main.go

How to dynamically render in elements?

I know "issues" probably isn't the correct place to ask a question, but seeing as the rocket.chat isn't very used, I'll ask here.

I'm trying to add a unspecified amount of <li> elements to my <ul>. How could I achieve this?

I didn't see anything about this in the examples. If I am wrong, my apologies

Middlewares are for all routes or not ?

I think that there is a behavior that can be improved.

First, i'd like to known if that behavior is wanted.

Consider the following code:

package main

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
)

func main() {
    app := iris.New()

    app.Get("/path1.txt", func(ctx context.Context) {
        ctx.Text("PATH1")
    })

    app.Use(func(ctx context.Context) {
        ctx.Text("MIDDLEWARE\n")
        ctx.Next()
    })

    app.Get("/path2.txt", func(ctx context.Context) {
        ctx.Text("PATH2")
    })

    app.Run(iris.Addr(":8080"))
}

With curl http://localhost:8080/path2.txt ; echo, we have:

MIDDLEWARE
PATH2

Okay.
But, with curl http://localhost:8080/path1.txt ; echo, we have:

PATH1

I understand why. That's cause the middleware is defined after "/path1.txt" route.
But even if it could be weird, i expected

MIDDLEWARE
PATH1

Was it wanted by you? I can understand this way for configuring the server.

The reason why i expected

MIDDLEWARE
PATH1

is a question of design.

The configurators are powerful to configure the server cause thet can be considered as plugin for example by making: app.Configure(plugin1, plugin2, ...), we have the choice to add securities, redirections, authentications, etc. or not.

It can arrive that in a configurator we can add routes but these routes must have managements defined in another configurator, even if it appears after in the configurator list.

I know how to implements this way to use middleware. Even more, i can add easily a parameter somewhere to activate this behavior. So the developer have the choice to use or not and then we have the old behavior.

I can send a PR for that. Cause the solution is simple. Today, when we make a route, the handler list is copied in the new route, so every route has its own copy of handler list. Instead of doing a copy, we should have a reference to a common handler list in the route.

Bug (This site can't be reached) when using ctx.Gzip(true) together with ctx.NotFound()

This is my code:

func main() {
	app := iris.New()
	
	app.Use(func(ctx context.Context) {
            ctx.Gzip(true)
            ctx.Next()
	})

	app.Handle("GET", "/", func(ctx context.Context) {
	    ctx.NotFound()
	})

	app.OnErrorCode(404, func(ctx context.Context) {
	     ctx.Writef("My Custom 404 error page ")
	 })

	app.Run(iris.Addr(":8082"))
}

If I navigate to homepage I get "This site can’t be reached" in Chrome, instead of the 404 Custom error page.

cvvvvv

Any thoughts?

Problem for {%extends%} in Django Engine with embedded files

When we use Django Engine for views (Pongo2), there is a problem for using embedded files, i meant by using DjangoEngine#Binary() method with "assets" function produced by go-bindata package.

The {%extends%} tag refers to physical file and not to embedded file (it searchs parent template on hard disk).

It may be a problem with tag implementation in Pongo2 but i didn't go further in my investigations.

Here is an example:

package main

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
	"os"
)

var files = map[string]string{
	"views/parent.html": `<!DOCTYPE html>
		<html>
			<head>
				<title>Iris with Pongo2 template engine</title>
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
				<meta http-equiv="Pragma" content="no-cache">
				<meta http-equiv="cache-control" content="no-cache">
			</head>
			<body>
				{% block body %}{% endblock %}
			</body>
		</html>`,

	"views/child.html": `{% extends "parent.html" %}
		{% block body %}
			Hello World !
		{% endblock %}`,
}

func get_names() []string {
	var res []string

	for name := range files {
		res = append(res, name)
	}

	return res
}

func get_files(name string) ([]byte, error) {
	content, exists := files[name]
	if !exists {
		return nil, os.ErrNotExist
	}

	return []byte(content), nil
}

func main() {
	app := iris.New()

	engine := iris.Django("views/", ".html")
	engine.Binary(get_files, get_names)

	app.RegisterView(engine)

	app.Get("/", func(ctx context.Context) {
		ctx.View("child.html")
	})

	app.Run(iris.Addr(":8080"))
}

It prints:

ERRO[0000] view: [Error (where: fromfile) in parent.html] open /home/frederic/go/src/prototypes/iris_django/parent.html: no such file or directory

MVC how to use multiple Handler?

Hi, I can't finde any info about how to use multiple handler for a function in a controller.

I would like to use for some routes(funcs) a pre handler func, that checks if a user is loggedIn and load then the needed Informations, else it should Skip the next handler and use the next after it.

Is there a possibility for that? Or need I code that all now in one handle?

with https://github.com/googollee/go-socket.io

i have an issue with https://github.com/googollee/go-socket.io at the current version of iris.
my main function:

func main(){
   app := iris.New()
	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	server.On("connection", func(so socketio.Socket) {
		log.Println("on connection")
		so.Join("chat")
		so.On("chat message", func(msg string) {
			log.Println("emit:", so.Emit("chat message", msg))
			so.BroadcastTo("chat", "chat message", msg)
		})
		so.On("disconnection", func() {
			log.Println("on disconnect")
		})
	})
	server.On("error", func(so socketio.Socket, err error) {
		log.Println("error:", err)
	})
	
	app.Any("/socket.io", iris.FromStd(server))
       	app.Run(iris.Addr(":8080"))
}

but the client always get 301 error code
please help me to fix it. THX

undefined iris.Context

I can't run application. it says undefined iris.Context.

app.Handle("GET", "/", func(ctx iris.Context) {
        ctx.HTML("<b>Welcome!</b>")
})

can not build a new pongo2 tag or filter

  1. can not port function use alias (view.Value,view.Parser,view.INodeTag...)
  2. can not implment INodeTag which is returned by TagParser(Execute in INodeTag has pongo2 params with no iris.view alias)

Guidelines for Iris structure?

Do Iris have standard structure?
Sorry that I'm still new to GoLang, but i wish to build my mobile app backend API with Iris. The problem i face is I dunno where to start from because I have already used to the framework with generator like Angular2, Ionic, Android. These frameworks come with tools that can generate folder structure and main file needed. I have go through other Go framework like Revel, Beego also but most of the review said Iris is the fastest one and this make me decide to use Iris to build my API.

As from Beego docs, it do have MVC structure like below:
β”œβ”€β”€ conf
β”‚ └── app.conf
β”œβ”€β”€ controllers
β”‚ β”œβ”€β”€ admin
β”‚ └── default.go
β”œβ”€β”€ main.go
β”œβ”€β”€ models
β”‚ └── models.go
β”œβ”€β”€ static
β”‚ β”œβ”€β”€ css
β”‚ β”œβ”€β”€ ico
β”‚ β”œβ”€β”€ img
β”‚ └── js
└── views
β”œβ”€β”€ admin
└── index.tpl
**We can see the M (models), V (views), C (controllers) folders. main.go is the entry point.

And below is from Revel
image

Will Iris come out a CLI tools? Or can guide me on this with an example?
I wish to build a AIM stack!
Angular2 (UI) + Iris (API) + MongoDB

may u add these functions?

may u add these functions?

context.URLParamBool(name string) (bool,error)
context.URLParamTrim(name string) string
context.URLParamEscape(name string) string
context.URLParamFloat64(name string) (float64, error)

context.PostValueTrim(name string) string
context.PostValueEscape(name string) string
context.PostBool(name string) (bool,error)
context.PostInt(name string) (int, error)
context.PostInt64(name string) (int64, error)
context.PostFloat64(name string) (float64, error)
context.PostStrings(name string) ([]string, error)

context.Params().GetTrim(name string) string
context.Params().GetEscape(name string) string
context.Params().GetBool(name string) (bool,error)
context.Params().GetFloat64(name string) (float64, error)

Orm support?

Documentation for the iris project can be found at
https://github.com/kataras/iris#-learn.

Since Iris started to include mvc model, is it going to support ORM for dealing with databases? In Node.JS there's something called Mongoose who's very productive;)

undefined: blackfriday with govendor

iris: 8.4.2
go: 1.9

Using iris with govendor package, I can't get it run locally ( via go run .. ) and remotly ( using heroku )

The error is the same and it is:

vendor/github.com/kataras/iris/context/context.go:2198:9: undefined: blackfriday.Run

Steps to reproduce:
-> Create new folder
-> Add in it main.go ( hello world tutorial )
-> govendor init
-> govendor fetch github.com/kataras/iris
-> go run main.go

I can't say much more, I don't know if i just missing something or if it's not a iris problem and i should open an issue on govendor.

Missing RFC2616 "Accept-Language" support by the i18n middleware

Hi!

Hope that I'm submitting to the correct repository.

Started used iris quite a while back and wanted to implement the i18n support today. Unfortunately, I had to notice that the middleware does not support the RFC2616 standard for the "Accept-Language" request header and therefore lacks an important feature for modern browsers.

Source
https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html (Section 14.4)

Problem
Incoming request with the "Accept-Language" header like de,de-DE:q=0.8,en-US;q=0.4 is not properly used for validating the language preferred by the user. The middleware simply forwards the full header which is not recognizable by unkwons i18n toolkit

///  "kataras/iris/middleware/i18n/i18n.go, line 33ff
if langHeader := ctx.RequestHeader("Accept-Language"); i18n.IsExist(langHeader) {
	language = langHeader
}

The following is a possible solution, which still ignores the given property q and does not fix the issue with replacement IETF language tags (e.g. en instead of en-US) - latter should be fixed by unkwon.

// try to get by the request headers
langHeader := ctx.RequestHeader("Accept-Language")
  if len(langHeader) > 0 {
    for _, langEntry := range strings.Split(langHeader, ",") {
      parts := strings.Split(langEntry, ";")
      if i18n.IsExist(parts[0]) {
        language = parts[0]
        break
      }
    }
  }

I can provide a proper merge request if you like.

Kind Regards,

CORS middleware cause next handler to be called 2 times

This ticket is following this ignored and closed one : #712

I took the example code available here and add a simple handler to bring out a bug.

package main

// $ go get github.com/rs/cors
// $ go run main.go

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/context"

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

	v1 := app.Party("/api/v1")

	v1.Use(crs, TestHandler)
	{
		v1.Get("/home", func(ctx context.Context) {
			ctx.WriteString("Hello from /home")
		})
		v1.Get("/about", func(ctx context.Context) {
			ctx.WriteString("Hello from /about")
		})
		v1.Post("/send", func(ctx context.Context) {
			ctx.WriteString("sent")
		})
	}

	// or use that to wrap the entire router
	// even before the path and method matching
	// this should work better and with all cors' features.
	// Use that instead, if suits you.
	// app.WrapRouter(cors.WrapNext(cors.Options{
	// 	AllowedOrigins:   []string{"*"},
	// 	AllowCredentials: true,
	// }))
	app.Run(iris.Addr("localhost:8080"))
}

func TestHandler(ctx context.Context) {
	ctx.Application().Logger().Info("TestHandler ", ctx)
	ctx.Next()
}

Expected result

Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.
?[36m[INFO]?[0m 2017/08/10 01:11 TestHandler &{0xc0423d0150 0xc0423da000 {[]} [] 0xc0422b8fc0 [0x7dda80 0x862960 0x862ab0] 0}

But got this

Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.
?[36m[INFO]?[0m 2017/08/10 01:11 TestHandler &{0xc0423d0150 0xc0423da000 {[]} [] 0xc0422b8fc0 [0x7dda80 0x862960 0x862ab0] 0}
?[36m[INFO]?[0m 2017/08/10 01:11 TestHandler &{0xc0423d0150 0xc0423da000 {[]} [] 0xc0422b8fc0 [0x7dda80 0x862960 0x862ab0] 1}

Something is clearly wrong ! πŸ˜„

Can we get the reporter?

Hello,

Even if the reporter has exported methods, we can't get the reported configured neither in in Application nor in APIBuilder structure.

However, if we had an GetReporter method on them for getting the reporter, we could call Add or AddErr methods on a reporter.

MVC: Support for RegEx?

Hi is there a potential to support RegEx for URLParams?
Or what is the best approach to use RegEx on the Params?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.