Giter Club home page Giter Club logo

examples's People

Contributors

albertpurnama avatar amanvir avatar corebreaker avatar hasheddan avatar hiveminded avatar ivancduran avatar kataras avatar maxwell92 avatar ooghry avatar tamsanh avatar uicosp avatar umarquez avatar zaniadeveloper 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

examples's Issues

Flash Session [ Help Needed ]

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

missing uploads folder on file_upload_simple example

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

Gzip doesn't 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.

bbbb

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?

WebSocket to REST handlers Adapter

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

Potential import collision: import path should be "go.etcd.io/bbolt", not "github.com/etcd-io/bbolt"

Background

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.

Solution

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

Serve SPA files and /api route

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

why static file can't be packaged

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 :
image
my dir structure is :
image
generated file is :
image

I can access normally when I don't build, anything wrong or my dir structure wrong?

"WithoutVersionChecker" is undefined!

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...

read form example cannot run

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?

More examples with partials in templates

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.

Any example of this code???

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

[Question] Custom Context

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

How to print Session value in Template

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"

Recovery's logger change

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

write tcp [::1]:8099->[::1]:64820: wsasend: An established connection was aborted by the software in your host machine.

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.

get with params

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

Error with ctx.URLParams()

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)

result

params: map[success:falsecanceled=false]
success=falsecanceled=false

how to read data from client like JMeter

I want to do load-test using tool JMeter.
The test-steps include:

  1. client sends a message (eg. a single string or key-value object) to a server
  2. Then the server receives the message and return back the string value to client

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!

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.