예제 #1
0
func TestConfigStatic(t *testing.T) {
	def := iris.DefaultConfiguration()

	api := iris.New(def)
	afterNew := *api.Config

	if !reflect.DeepEqual(def, afterNew) {
		t.Fatalf("Default configuration is not the same after NewFromConfig expected:\n %#v \ngot:\n %#v", def, afterNew)
	}

	afterNew.Charset = "changed"

	if reflect.DeepEqual(def, afterNew) {
		t.Fatalf("Configuration should be not equal, got: %#v", afterNew)
	}

	api = iris.New(iris.Configuration{IsDevelopment: true})

	afterNew = *api.Config

	if api.Config.IsDevelopment == false {
		t.Fatalf("Passing a Configuration field as Option fails, expected IsDevelopment to be true but was false")
	}

	api = iris.New() // empty , means defaults so
	if !reflect.DeepEqual(def, *api.Config) {
		t.Fatalf("Default configuration is not the same after NewFromConfig expected:\n %#v \ngot:\n %#v", def, *api.Config)
	}
}
예제 #2
0
func TestCustomErrors(t *testing.T) {
	api := iris.New()
	// first register the routes needed
	for _, r := range routesCustomErrors {
		if r.Register {
			api.HandleFunc(r.Method, r.Path, func(ctx *iris.Context) {
				ctx.EmitError(r.Status)
			})
		}
	}

	// register the custom errors
	api.OnError(404, func(ctx *iris.Context) {
		ctx.Write("%s", notFoundMessage)
	})

	api.OnError(500, func(ctx *iris.Context) {
		ctx.Write("%s", internalServerMessage)
	})

	// create httpexpect instance that will call fasthtpp.RequestHandler directly
	e := httpexpect.WithConfig(httpexpect.Config{
		Reporter: httpexpect.NewAssertReporter(t),
		Client:   fasthttpexpect.NewBinder(api.NoListen().Handler),
	})

	// run the tests
	for _, r := range routesCustomErrors {
		e.Request(r.Method, r.RequestPath).
			Expect().
			Status(r.Status).Body().Equal(r.Body)
	}
}
예제 #3
0
func TestConfigOptions(t *testing.T) {
	charset := "MYCHARSET"
	dev := true

	api := iris.New(iris.OptionCharset(charset), iris.OptionIsDevelopment(dev))

	if got := api.Config.Charset; got != charset {
		t.Fatalf("Expected configuration Charset to be: %s but got: %s", charset, got)
	}

	if got := api.Config.IsDevelopment; got != dev {
		t.Fatalf("Expected configuration IsDevelopment to be: %#v but got: %#v", dev, got)
	}

	// now check if other default values are setted (should be setted automatically)

	expected := iris.DefaultConfiguration()
	expected.Charset = charset
	expected.IsDevelopment = dev

	has := *api.Config
	if !reflect.DeepEqual(has, expected) {
		t.Fatalf("Default configuration is not the same after New expected:\n %#v \ngot:\n %#v", expected, has)
	}
}
예제 #4
0
func main() {
	api := iris.New()
	api.Get("/rest/hello", func(c *iris.Context) {
		c.Text("Hello world")
	})
	api.Listen(":8080")
}
예제 #5
0
파일: route_test.go 프로젝트: cokeboL/iris
func TestPathEscape(t *testing.T) {
	api := iris.New()

	api.Get("/details/:name", func(ctx *iris.Context) {
		name := ctx.Param("name")
		highlight := ctx.URLParam("highlight")
		ctx.Text(iris.StatusOK, fmt.Sprintf("name=%s,highlight=%s", name, highlight))
	})

	e := httpexpect.WithConfig(httpexpect.Config{Reporter: httpexpect.NewAssertReporter(t), Client: fasthttpexpect.NewBinder(api.NoListen().Handler)})

	e.Request("GET", "/details/Sakamoto desu ga?highlight=text").Expect().Status(iris.StatusOK).Body().Equal("name=Sakamoto desu ga,highlight=text")
}
예제 #6
0
파일: server.go 프로젝트: plimble/ivy
func NewServer(config *Config) (*iris.Framework, error) {
	ir := iris.New(
		iris.OptionDisableBanner(true),
	)

	source := NewS3(config.SourceAwsId, config.SourceAwsSecret, config.SourceAwsS3Bucket, config.SourceAwsS3Region)

	p := NewProcessor(source)

	ir.Get("/*path", handler(p))

	return ir, nil
}
예제 #7
0
파일: route_test.go 프로젝트: cokeboL/iris
func TestRouter(t *testing.T) {
	api := iris.New()
	for idx := range routes {
		r := routes[idx]
		if r.Register {
			api.HandleFunc(r.Method, r.Path, func(ctx *iris.Context) {
				ctx.SetStatusCode(r.Status)
				if r.Params != nil && len(r.Params) > 0 {
					ctx.SetBodyString(ctx.Params.String())
				} else if r.UrlParams != nil && len(r.UrlParams) > 0 {
					if len(r.UrlParams) != len(ctx.URLParams()) {
						t.Fatalf("Error when comparing length of url parameters %d != %d", len(r.UrlParams), len(ctx.URLParams()))
					}
					paramsKeyVal := ""
					for idxp, p := range r.UrlParams {
						val := ctx.URLParam(p.Key)
						paramsKeyVal += p.Key + "=" + val + ","
						if idxp == len(r.UrlParams)-1 {
							paramsKeyVal = paramsKeyVal[0 : len(paramsKeyVal)-1]
						}
					}
					ctx.SetBodyString(paramsKeyVal)
				} else {
					ctx.SetBodyString(r.Body)
				}

			})
		}
	}

	// create httpexpect instance that will call fasthtpp.RequestHandler directly
	e := httpexpect.WithConfig(httpexpect.Config{
		Reporter: httpexpect.NewAssertReporter(t),
		Client:   fasthttpexpect.NewBinder(api.NoListen().Handler),
	})

	// run the tests (1)
	for idx := range routes {
		r := routes[idx]
		e.Request(r.Method, r.RequestPath).
			Expect().
			Status(r.Status).Body().Equal(r.Body)
	}

}
예제 #8
0
func TestConfigOptionsDeep(t *testing.T) {
	cookiename := "MYSESSIONID"
	charset := "MYCHARSET"
	dev := true
	vhost := "mydomain.com"
	// first session, after charset,dev and profilepath, no canonical order.
	api := iris.New(iris.OptionSessionsCookie(cookiename), iris.OptionCharset(charset), iris.OptionIsDevelopment(dev), iris.OptionVHost(vhost))

	expected := iris.DefaultConfiguration()
	expected.Sessions.Cookie = cookiename
	expected.Charset = charset
	expected.IsDevelopment = dev
	expected.VHost = vhost

	has := *api.Config

	if !reflect.DeepEqual(has, expected) {
		t.Fatalf("DEEP configuration is not the same after New expected:\n %#v \ngot:\n %#v", expected, has)
	}
}
예제 #9
0
func startIris() {
	mux := iris.New()
	mux.Get("/hello", irisHandler)
	mux.Listen(":" + strconv.Itoa(port))
}
예제 #10
0
// IrisHandler creates fasthttp.RequestHandler using Iris web framework.
func IrisHandler() fasthttp.RequestHandler {
	api := iris.New()

	api.Get("/things", func(c *iris.Context) {
		c.JSON(iris.StatusOK, []interface{}{
			iris.Map{
				"name":        "foo",
				"description": "foo thing",
			},
			iris.Map{
				"name":        "bar",
				"description": "bar thing",
			},
		})
	})

	api.Post("/redirect", func(c *iris.Context) {
		c.Redirect("/things", iris.StatusFound)
	})

	api.Get("/params/:x/:y", func(c *iris.Context) {
		c.JSON(iris.StatusOK, iris.Map{
			"x":  c.Param("x"),
			"y":  c.Param("y"),
			"q":  c.URLParam("q"),
			"p1": c.FormValueString("p1"),
			"p2": c.FormValueString("p2"),
		})
	})

	auth := basicauth.Default(map[string]string{
		"ford": "betelgeuse7",
	})

	api.Get("/auth", auth, func(c *iris.Context) {
		c.Write("authenticated!")
	})

	api.Post("/session/set", func(c *iris.Context) {
		sess := iris.Map{}

		if err := c.ReadJSON(&sess); err != nil {
			panic(err.Error())
		}

		c.Session().Set("name", sess["name"])
	})

	api.Get("/session/get", func(c *iris.Context) {
		name := c.Session().GetString("name")

		c.JSON(iris.StatusOK, iris.Map{
			"name": name,
		})
	})

	api.Get("/stream", func(c *iris.Context) {
		c.StreamWriter(func(w *bufio.Writer) {
			for i := 0; i < 10; i++ {
				fmt.Fprintf(w, "%d", i)

				if err := w.Flush(); err != nil {
					return
				}
			}
		})
	})

	api.Post("/stream", func(c *iris.Context) {
		c.Write(string(c.Request.Body()))
	})

	sub := api.Party("subdomain.")

	sub.Post("/set", func(c *iris.Context) {
		c.Session().Set("message", "hello from subdomain")
	})

	sub.Get("/get", func(c *iris.Context) {
		c.Write(c.Session().GetString("message"))
	})

	return api.ListenVirtual().Handler
}
예제 #11
0
파일: iriscontrol.go 프로젝트: cokeboL/iris
func (i *iriscontrol) initializeChild() {
	i.child = iris.New()
	i.child.Config.DisableBanner = true
	i.child.Config.Render.Template.Directory = assetsPath + "templates"
	i.child.Config.Websocket.Endpoint = "/ws"

	// set the assets
	i.child.Static("/public", assetsPath+"static", 1)

	// set the authentication middleware to all except websocket
	auth := basicauth.New(config.BasicAuth{
		Users:      i.users,
		ContextKey: "user",
		Realm:      config.DefaultBasicAuthRealm,
		Expires:    time.Duration(1) * time.Hour,
	})

	i.child.UseFunc(func(ctx *iris.Context) {
		///TODO: Remove this and make client-side basic auth when websocket connection. (user@password/host.. on chronium)
		// FOR GOOGLE CHROME/CHRONIUM
		// https://bugs.chromium.org/p/chromium/issues/detail?id=123862
		// CROSS DOMAIN IS DISABLED so I think this is ok solution for now...
		if ctx.PathString() == i.child.Config.Websocket.Endpoint {
			ctx.Next()
			return
		}
		auth.Serve(ctx)
	})

	i.child.Websocket.OnConnection(func(c websocket.Connection) {
		// add the client to the list
		i.clients = append(i.clients, c)
		c.OnDisconnect(func() {
			// remove the client from the list
			if idx := i.clients.indexOf(c.ID()); idx != -1 {
				i.clients[idx] = i.clients[len(i.clients)-1]
				i.clients = i.clients[:len(i.clients)-1]
			}

		})
	})

	i.child.Get("/", func(ctx *iris.Context) {
		ctx.MustRender("index.html", iris.Map{
			"ServerIsRunning":      i.parentIsRunning(),
			"Host":                 i.child.Config.Server.ListeningAddr,
			"Routes":               i.parentLookups(),
			"Plugins":              i.infoPlugins(),
			"LastOperationDateStr": i.infoLastOp(),
		})
	})

	i.child.Post("/start_server", func(ctx *iris.Context) {

		if !i.parentIsRunning() {
			// starts the server with its old configuration
			go func() {
				if err := i.parent.HTTPServer.Open(); err != nil {
					i.parent.Logger.Warningf(err.Error())
				}
			}()

			i.parentLastOp = time.Now()
		}
	})

	i.child.Post("/stop_server", func(ctx *iris.Context) {

		if i.parentIsRunning() {
			i.parentLastOp = time.Now()

			go func() {
				if err := i.parent.CloseWithErr(); err != nil {
					i.parent.Logger.Warningf(err.Error())
				}
			}()
		}
	})

	go i.child.Listen(i.parent.HTTPServer.VirtualHostname() + ":" + strconv.Itoa(i.port))
}