Esempio n. 1
0
func TestGetFromContextNoIp(t *testing.T) {
	var ctx iris.Context
	ctx.RequestCtx = &fasthttp.RequestCtx{}
	ip := GetFromContext(&ctx)

	assert.Equal(t, ip, "", "Should not find an ip address.")
}
Esempio n. 2
0
func TestGetFromContextWithGlobalAndPrivateForwardedIps(t *testing.T) {
	var ctx iris.Context
	ctx.RequestCtx = &fasthttp.RequestCtx{}
	header := fasthttp.RequestHeader{}
	header.Add("X-Forwarded-For", "65.55.37.104, 100.64.0.0, 192.168.0.0, 192.0.0.0")
	ctx.RequestCtx.Request.Header = header
	ip := GetFromContext(&ctx)

	assert.Equal(t, ip, "65.55.37.104", "Should be the first ip, which is the global ip address.")
}
Esempio n. 3
0
func TestGetFromContextWithPrivateForwadedIp(t *testing.T) {
	var ctx iris.Context
	ctx.RequestCtx = &fasthttp.RequestCtx{}
	header := fasthttp.RequestHeader{}
	header.Add("X-Forwarded-For", "100.64.0.0, 192.168.0.0")
	ctx.RequestCtx.Request.Header = header
	ip := GetFromContext(&ctx)

	assert.Equal(t, ip, "", "Should not find an ip address.")
}
Esempio n. 4
0
func (r recovery) Serve(ctx *iris.Context) {
	defer func() {
		if err := recover(); err != nil {
			r.out.Write([]byte("[" + time.Now().String() + "]Recovery from panic \n"))
			//ctx.Panic just sends  http status 500 by default, but you can change it by: iris.OnPanic(func( c *iris.Context){})
			ctx.Panic()
		}
	}()
	ctx.Next()
}
Esempio n. 5
0
func getMessage(c *iris.Context) {
	t := sb.NewTable(
		"chats",
		sb.StrColumn("roomid", sb.UTF8, sb.UTF8CaseSensitive, false),
		sb.StrColumn("text", sb.UTF8, sb.UTF8CaseSensitive, false),
	)
	query, _ := t.Select(t.C("roomid"), t.C("text")).String("chat")
	rows, err := db.Query(query)
	if err != nil {
		log.Fatal(err)
	}
	var messages []string
	for rows.Next() {
		var roomid string
		var text string
		if err := rows.Scan(&roomid, &text); err != nil {
			log.Fatal(err)
		}
		messages = append(messages, text)
	}
	c.JSON(iris.StatusOK, map[string][]string{"messages": messages})
}
Esempio n. 6
0
// Serve the actual middleware
func (b *basicAuthMiddleware) Serve(ctx *iris.Context) {

	if auth, found := b.findAuth(ctx.RequestHeader("Authorization")); !found {
		/* I spent time for nothing
		if b.banEnabled && auth != nil { // this propably never work

			if auth.tries == b.config.MaxTries {
				auth.bannedTime = time.Now()
				auth.unbanTime = time.Now().Add(b.config.BanDuration) // set the unban time
				auth.tries++                                          // we plus them in order to check if already banned later
				// client is banned send a forbidden status and don't continue
				ctx.SetStatusCode(iris.StatusForbidden)
				return
			} else if auth.tries > b.config.MaxTries { // it's already banned, so check the ban duration with the bannedTime
				if time.Now().After(auth.unbanTime) { // here we unban the client
					auth.tries = 0
					auth.bannedTime = config.CookieExpireNever
					auth.unbanTime = config.CookieExpireNever
					// continue and askCredentials as normal
				} else {
					// client is banned send a forbidden status and don't continue
					ctx.SetStatusCode(iris.StatusForbidden)
					return
				}

			}
		}
		if auth != nil {
			auth.tries++
		}*/

		b.askForCredentials(ctx)
		// don't continue to the next handler
	} else {
		// all ok set the context's value in order to be getable from the next handler
		ctx.Set(b.config.ContextKey, auth.Username)
		if b.expireEnabled {

			if auth.logged == false {
				auth.expires = time.Now().Add(b.config.Expires)
				auth.logged = true
			}

			if time.Now().After(auth.expires) {
				b.askForCredentials(ctx) // ask for authentication again
				return
			}

		}

		//auth.tries = 0
		ctx.Next() // continue
	}

}
Esempio n. 7
0
// Serve serves the middleware
func (l *LoggerMiddleware) Serve(ctx *iris.Context) {
	//all except latency to string
	var date, status, ip, method, path string
	var latency time.Duration
	var startTime, endTime time.Time

	status = strconv.Itoa(ctx.Response.StatusCode())
	ip = ctx.RemoteAddr()
	path = ctx.PathString()
	method = ctx.MethodString()

	startTime = time.Now()
	ctx.Next()
	//no time.Since in order to format it well after
	endTime = time.Now()
	date = endTime.Format("01/02 - 15:04:05")
	latency = endTime.Sub(startTime)

	//finally print the logs
	l.printf("%s %v %4v %s %s %s", date, status, latency, ip, method, path)
}
Esempio n. 8
0
func (m *myTestCustomHandler) Serve(ctx *iris.Context) {
	data := &m.data
	data.DynamicPathParameter = ctx.Param("myparam")
	ctx.JSON(iris.StatusOK, data)
}
// iris
func irisHandler(c *iris.Context) {
	if sleepTime > 0 {
		time.Sleep(sleepTimeDuration)
	}
	c.SetBody(message)
}
Esempio n. 10
0
// White-box testing *
func TestContextDoNextStop(t *testing.T) {
	var context iris.Context
	ok := false
	afterStop := false
	context.Middleware = iris.Middleware{iris.HandlerFunc(func(*iris.Context) {
		ok = true
	}), iris.HandlerFunc(func(*iris.Context) {
		ok = true
	}), iris.HandlerFunc(func(*iris.Context) {
		// this will never execute
		afterStop = true
	})}
	context.Do()
	if context.Pos != 0 {
		t.Fatalf("Expecting position 0 for context's middleware but we got: %d", context.Pos)
	}
	if !ok {
		t.Fatalf("Unexpected behavior, first context's middleware didn't executed")
	}
	ok = false

	context.Next()

	if int(context.Pos) != 1 {
		t.Fatalf("Expecting to have position %d but we got: %d", 1, context.Pos)
	}
	if !ok {
		t.Fatalf("Next context's middleware didn't executed")
	}

	context.StopExecution()
	if context.Pos != 255 {
		t.Fatalf("Context's StopExecution didn't worked, we expected to have position %d but we got %d", 255, context.Pos)
	}

	if !context.IsStopped() {
		t.Fatalf("Should be stopped")
	}

	context.Next()

	if afterStop {
		t.Fatalf("We stopped the execution but the next handler was executed")
	}
}
Esempio n. 11
0
func (b *basicAuthMiddleware) askForCredentials(ctx *iris.Context) {
	ctx.SetHeader("WWW-Authenticate", b.realmHeaderValue)
	ctx.SetStatusCode(iris.StatusUnauthorized)
}
Esempio n. 12
0
//Important staff, iris middleware must implement the iris.Handler interface which is:
func (m MyGlobalMiddlewareStructed) Serve(c *iris.Context) {
	fmt.Println("Hello from logger with id: ", m.loggerId)
	c.Next()
}
Esempio n. 13
0
func handleError(ctx *iris.Context, message string, err error) {
	fmt.Printf("%v", err)
	ctx.Error(message, 503)
}