iris-contrib / examples Goto Github PK
View Code? Open in Web Editor NEWThis repository contains small and practical examples for the Iris Web Framework.
Home Page: https://iris-go.com
License: MIT License
This repository contains small and practical examples for the Iris Web Framework.
Home Page: https://iris-go.com
License: MIT License
I have below code , main intention is to return flash error - but it is not working at all.
While I go to Login page and process the request - It shows error in command line, but when it is redirected to login page - the error is blank.
msess := memorySess()
app.Get("/login", func(ctx context.Context) {
s := msess.Start(ctx)
error := s.GetFlashString("Error")
if error != "" {
ctx.ViewData("Error", error)
}
fmt.Printf("Login Error %s\n", error)
success := s.GetFlashString("Success")
if error != "" {
ctx.ViewData("Success", success)
}
fmt.Printf("Success Error %s\n", error)
ctx.ViewData("Title", "Login")
if err := ctx.View("login.html"); err != nil {
ctx.Application().Logger().Infof(err.Error())
}
})
app.Post("do/login", postLogin(db))
and here are 2 function
func memorySess() *sessions.Sessions {
tempSess := sessions.New(sessions.Config{
Cookie: "simpleCoolCookie",
})
return tempSess
}
func postLogin(db *sql.DB) context.Handler {
return func(ctx context.Context) {
sess := memorySess()
s := sess.Start(ctx)
rows, err := db.Prepare("select * from users where username = ? or mobile = ? limit 1")
if err != nil {
s.SetFlash("Error", err.Error())
fmt.Printf("Prepare Error: %s\n", err.Error())
ctx.Redirect("/login", 302)
} else {
var user users
regis := &logUser{
Username: ctx.FormValue("login_id"),
Mobile: ctx.FormValue("login_id"),
Password: ctx.FormValue("login_password"),
}
_, err := valid.ValidateStruct(regis)
if err != nil {
s.SetFlash("Error", err.Error())
fmt.Printf("Validate Error: %s\n", err.Error())
ctx.Redirect("/login", 302)
}
}
}
}
Just installed iris.v6 today and , downloaded this repo and tried to run
https://github.com/iris-contrib/examples/tree/master/file_upload_simple
cd file_upload_simple
go run main.go
The server executes and http://127.0.0.1:8080/upload is available, but after the upload get the message: Error while uploading: open ./uploads/Screen Shot 2017-02-21 at 4.52.14 PM.png: no such file or directory
I get no logs in the console either, either of what worked or didn't (which maybe is a bug on iris?)
If i mkdir uploads
then it seems to work
I am trying to enable gzip for all the website, but getting the following error in the browser's
console for my static files: "Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH".
If I disable Gzip everything works fine.
This is the code I've used inside Iris:
app = iris.New()
app.Use(func(ctx context.Context) {
ctx.Gzip(true)
})
I am using the latest version of Iris, Ubuntu 16.04 and Chrome.
Any thoughts?
Hi Kataras,
I think the PUT and POST methods were used incorrectly in examples/api_handler_2/main.go.
Have a look at the discuss on stackoverflow http://stackoverflow.com/questions/630453/put-vs-post-in-rest.
Also, http://restcookbook.com/HTTP%20Methods/put-vs-post/
i have some problem,please help me,thanks~~~
https://github.com/mini-docker/secondsKill/tree/master/yyccQQu-iris
http://localhost:8080/hello
Internal Server Error~
Hi kataras and other contributors.
I use Iris framework to build REST api. I also added websockets to the project. And now I got an idea to use business logic of the REST api together with my socket controller. I want to build an adapter from websocket to http handlers for reuse code.
It will much improve response time, because it will pass authentication middleware only once per connection, it will not do tcp, ssl handshaking every single request.
Socket will get a message in Iris json/binary format. Event name will be name of http (REST) route. And body of this message will be exact body for the REST.
REST handler will do BL and will write result in "virtual" context, managed by adapter. After that adapter will pass this response message to the socket. Event name of the response will be the same route of request.
I need your help to do it, and of course it will be part of iris-contrib repository.
Thanks
I use curl to simulate the post action, it return "Not Found",and it never step in PostBy() function.
`
curl -d "name=12" http://localhost:8080/users/
curl -d "name=12" http://localhost:8080/users/1/
`
The etcd-io/bbolt
has already renamed it’s import path from "github.com/etcd-io/bbolt" to "go.etcd.io/bbolt".
As etcd-io/bbolt README.md said, downstream repos should use "go.etcd.io/bbolt" to get or import etcd-io/bbolt
.
But iris-contrib/examples
still used the old path:
https://github.com/iris-contrib/examples/blob/v12/tutorial/url-shortener/go.mod#L6
github.com/etcd-io/bbolt v1.3.3
When you use the old path "github.com/etcd-io/bbolt" to import the etcd-io/bbolt
, will reintroduces etcd-io/bbolt
through the import statements "import go.etcd.io/bbolt" in the go source file of etcd-io/bbolt
.
https://github.com/etcd-io/bbolt/blob/v1.3.3/cursor_test.go#L14
package bbolt_test
import (
bolt "go.etcd.io/bbolt"
…
)
The "go.etcd.io/bbolt" and "github.com/etcd-io/bbolt" are the same repos. This will work in isolation, bring about potential risks and problems.
So, why not get rid of the old import path "github.com/etcd-io/bbolt", use "go.etcd.io/bbolt" instead.
Replace all the old import paths, change "github.com/etcd-io/bbolt"
to "go.etcd.io/bbolt "
.
Where did you import it: https://github.com/iris-contrib/examples/search?q=github.com%2Fetcd-io%2Fbbolt&unscoped_q=github.com%2Fetcd-io%2Fbbolt
Is there any example with JWT tokens for Iris v7?
I've found this one https://github.com/iris-contrib/middleware/blob/master/jwt/_example/main.go (for Iris v6)
Hello there - I'm trying to configure iris to do a couple of things.
I want it to serve up static content for an angular SPA (in html5 mode) which means I will want to redirect all routes that don't start with /api to the static middleware, but for all actions below /api I will have custom handlers.
Code:
package main
import (
"github.com/kataras/iris"
// "github.com/kataras/iris/utils"
// "strings"
)
func allVendorBrandLabel(c *iris.Context) {
c.WriteString("Hello, api :)")
}
func main() {
iris.Get("/api/all", allVendorBrandLabel)
iris.StaticWeb("/", "./www", 2)
iris.Listen(":8080")
}
This results in the root route failing with a 404, but the /api/ call returns nominally.
What do I need to accomplish this?
I also posted the question to StackOverflow to see how I could get it working:
http://stackoverflow.com/questions/38922585/how-to-serve-api-and-html5-spa-with-iris
At present we can only call service in controllers. Expect such a way to call a service cross services.
I use your steps:
// $ go get -u github.com/shuLhan/go-bindata/...
// $ go-bindata ./templates/...
// $ go build
// $ ./embedding-templates-into-app
// html files are not used, you can delete the folder and run the example.
tmpl.Binary(Asset, AssetNames) // <-- IMPORTANT
my code is :
my dir structure is :
generated file is :
I can access normally when I don't build, anything wrong or my dir structure wrong?
Hello, Thanks for this amazing library,
I'm new to Go and Iris, I've installed examples (I've installed Iris too), but when I try to run the server by go run main.go
in overview directory, I get this error: .\main.go:77:57: undefined: iris.WithoutVersionChecker
I've also tried to comment iris.WithoutVersionChecker
in the code, the code will run after that but I get 404 not found
on all of request/routes...
when I run the example read_form
I got this result:
while trying to read formam: not found the field "mydata" in the path "mydata" from the request body. Trace %!s(MISSING)
Visitor: main.Visitor{Username:"kllk", Mail:"lkjk", Data:[]string(nil)}
Why?
https://github.com/iris-contrib/examples/blob/master/subdomains_simple/main.go#L32
When I build subdomains_simple example,
its process immediately shutdown.
And I could fix it if I changed the receiver port other than 80.
Is it a bug ? If not, could you tell me the solution?
Could an example be added to show how to use partials in the templates with Render? I've read through this section in the book and then made the following example but I'm still missing something as my partials are not rendered. So more details would be helpful.
I have the following:
$ tree
.
├── templates
│ ├── footer-layout.html
│ ├── header-layout.html
│ ├── layout.html
│ └── mypage.html
└── web.go
web.go
package main
import (
"github.com/kataras/iris"
)
type mypage struct {
Title string
Message string
}
func main() {
iris.Config().Render.Directory = "templates"
iris.Config().Render.Layout = "layout"
iris.Config().Render.Gzip = true
iris.Get("/", func(ctx *iris.Context) {
ctx.Render("mypage", mypage{"My Page title", "Hello world!"})
})
println("Server is running at :8080")
iris.Listen(":8080")
}
footer-layout.html
{{ define "footer-layout" }}
<h1>FOOTER</h1>
{{ end }}
header-layout.html
{{ define "header-layout" }}
<h1>HEADER</h1>
{{ end }}
layout.html
<!-- templates/layout.html -->
<html>
<head>
<title>My Layout</title>
</head>
<body>
<!-- render the partial template called `header-$current_template` here -->
{{ partial "header" }}
<!-- Render the current template here -->
{{ yield }}
<!-- render the partial template called `footer-$current_template` here -->
{{ partial "footer" }}
</body>
</html>
mypage.html
<h1>TEST</h1>
<h2>
{{.Title}}
<pre>{{.Message}}</pre>
</h2>
I figure it's something simple I'm missing. Can someone help me get this working?
Thanks.
How do I set up a header?
How to remove mandatory at the end/?
Hi, thanks for this good library, how to make http web server with iris like this, in bellow:
package main
import (
"flag"
"log"
"net/http"
)
func main() {
port := flag.String("p", "8100", "port to serve on")
directory := flag.String("d", ".", "build/index.html")
flag.Parse()
http.Handle("/", http.FileServer(http.Dir(*directory)))
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
Hi,
type MyContext struct {
*iris.Context
User string
}
func Contextor() iris.HandlerFunc {
return func (ctx *iris.Context){
c := &MyContext{
Context: ctx,
User: nil,
}
ctx.map(c)
}
}
iris.Use(Contextor())
Is this possible?
Sorry for my bad english
I am planning to save user-info from database in session and than printing the name and other value on header template.
Like Welcome Iris | Logout
Running query everytime looks bad idea, so I prefer to store the value in session and print them in template.
While I do, ctx.ViewData("user", user)
// Where user is struct against user table.
But as soon as I print them, I get "is not a method but has arguments"
Im a newer for iris.
My logs need rolling 3 files from recovery's loger, how to doing?
May also, the logger switch to github.com/$edited/$edited.
thx
I used MAC and VScode as my develop environment,
and it showed "No found" on the webpage "/create" and "decode"
API server listening at: 127.0.0.1:64767
Now listening on: http://localhost:8099
Application started. Press CTRL+C to shut down.
[ERRO] 2019/03/06 16:37 write tcp [::1]:8099->[::1]:64820: wsasend: An established connection was aborted by the software in your host machine.
[ERRO] 2019/03/06 16:37 write tcp [::1]:8099->[::1]:64821: wsasend: An established connection was aborted by the software in your host machine.
[ERRO] 2019/03/06 16:37 write tcp [::1]:8099->[::1]:64830: wsasend: An established connection was aborted by the software in your host machine.
I didn't see an example of How I get my code coverage from tests.
Hi @kataras
I am very new to scripting programming.
Can you help me with below doubt.
I have GET request with parameter say "/pass?result=33" , based on result value my response will differ. How I can achieve this using iris framework.
app.Get("/pass?{result:int}", func(ctx iris.Context) {
result, _ := ctx.Params().GetInt("result")
if result > 33 {
ctx.WriteString("Pass")
} else {
ctx.WriteString("Fail")
}
})
It is not working
the Method ctx.URLParams() returns a map, but it's not right.
params := ctx.URLParams()
var (
strSql string
)
if len(params) != 0 {
for k, v := range params {
strSql += fmt.Sprintf("%v=%v AND ", k, v)
}
}
strSql = strSql[0 : len(strSql)-4]
fmt.Printf("params: %+v \n", params)
fmt.Println(strSql)
params: map[success:falsecanceled=false]
success=falsecanceled=false
I want to do load-test using tool JMeter.
The test-steps include:
At present, I haven't found a func to help me finish my work.
I try to do coding as follows:
package main
import (
"fmt"
"github.com/kataras/iris"
"github.com/kataras/iris/websocket"
)
func main() {
app := iris.New()
ws := websocket.New(websocket.Config{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
})
ws.OnConnection(handleConnection)
app.Get("/echo", ws.Handler())
app.Run(iris.Addr(":8080"))
}
func handleConnection(c websocket.Connection) {
fmt.Println("read start...")
recvString := c.GetValueString("name")
fmt.Println("receive string is ",recvString)
c.EmitMessage([]byte(recvString))
}
I send a key-value {"name":"Clark"}
However I can get the right response
Can you help me, thanks very much!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.