Пример #1
0
func TestEcho(t *testing.T) {
	e := New()
	req, _ := http.NewRequest(GET, "/", nil)
	rec := httptest.NewRecorder()
	c := NewContext(req, NewResponse(rec, e), e)

	// Router
	assert.NotNil(t, e.Router())

	// Debug
	e.SetDebug(true)
	assert.True(t, e.debug)

	// DefaultHTTPErrorHandler
	e.DefaultHTTPErrorHandler(errors.New("error"), c)
	assert.Equal(t, http.StatusInternalServerError, rec.Code)

	// Logger
	l := log.New("test")
	e.SetLogger(l)
	assert.Equal(t, l, e.Logger())

	// Autoindex
	e.AutoIndex(true)
	assert.True(t, e.autoIndex)
}
Пример #2
0
// New creates an instance of Echo.
func New() (e *Echo) {
	e = &Echo{maxParam: new(int)}
	e.pool.New = func() interface{} {
		return NewContext(nil, new(Response), e)
	}
	e.router = NewRouter(e)

	//----------
	// Defaults
	//----------

	e.HTTP2(true)
	e.defaultHTTPErrorHandler = func(err error, c *Context) {
		code := http.StatusInternalServerError
		msg := http.StatusText(code)
		if he, ok := err.(*HTTPError); ok {
			code = he.code
			msg = he.message
		}
		if e.debug {
			msg = err.Error()
		}
		if !c.response.committed {
			http.Error(c.response, msg, code)
		}
		e.logger.Error(err)
	}
	e.SetHTTPErrorHandler(e.defaultHTTPErrorHandler)
	e.SetBinder(&binder{})

	// Logger
	e.logger = log.New("echo")

	return
}
Пример #3
0
func TestResponseWriteHeader(t *testing.T) {
	rec := httptest.NewRecorder()
	res := NewResponse(rec, log.New("test"))
	res.WriteHeader(http.StatusOK)
	assert.True(t, res.Committed())
	assert.Equal(t, http.StatusOK, res.Status())
}
Пример #4
0
func NewConfig(c *engine.Config) (s *Server) {
	s = &Server{
		Server: new(http.Server),
		config: c,
		pool: &Pool{
			request: sync.Pool{
				New: func() interface{} {
					return &Request{}
				},
			},
			response: sync.Pool{
				New: func() interface{} {
					return &Response{logger: s.logger}
				},
			},
			header: sync.Pool{
				New: func() interface{} {
					return &Header{}
				},
			},
			url: sync.Pool{
				New: func() interface{} {
					return &URL{}
				},
			},
		},
		handler: engine.HandlerFunc(func(req engine.Request, res engine.Response) {
			s.logger.Fatal("handler not set")
		}),
		logger: log.New("echo"),
	}
	return
}
Пример #5
0
// NewFromConfig returns an instance of `standard.Server` from config.
func NewFromConfig(c engine.Config) (s *Server) {
	s = &Server{
		Server: new(http.Server),
		config: c,
		pool: &pool{
			request: sync.Pool{
				New: func() interface{} {
					return &Request{logger: s.logger}
				},
			},
			response: sync.Pool{
				New: func() interface{} {
					return &Response{logger: s.logger}
				},
			},
			header: sync.Pool{
				New: func() interface{} {
					return &Header{}
				},
			},
			url: sync.Pool{
				New: func() interface{} {
					return &URL{}
				},
			},
		},
		handler: engine.HandlerFunc(func(rq engine.Request, rs engine.Response) {
			s.logger.Error("handler not set, use `SetHandler()` to set it.")
		}),
		logger: log.New("echo"),
	}
	s.Addr = c.Address
	s.Handler = s
	return
}
Пример #6
0
func TestLoggerIPAddress(t *testing.T) {
	e := echo.New()
	l := log.New("echo")
	buf := new(bytes.Buffer)
	l.SetOutput(buf)
	e.SetLogger(l)
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec, e), e)
	ip := "127.0.0.1"
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}

	mw := Logger()

	// With X-Real-IP
	req.Header.Add(echo.XRealIP, ip)
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)

	// With X-Forwarded-For
	buf.Reset()
	req.Header.Del(echo.XRealIP)
	req.Header.Add(echo.XForwardedFor, ip)
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)

	// with req.RemoteAddr
	buf.Reset()
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)
}
Пример #7
0
func TestResponseWrite(t *testing.T) {
	c := new(fasthttp.RequestCtx)
	res := NewResponse(c, log.New("test"))
	res.Write([]byte("test"))
	assert.Equal(t, int64(4), res.Size())
	assert.Equal(t, "test", string(c.Response.Body()))
}
Пример #8
0
func TestResponseWriteHeader(t *testing.T) {
	c := new(fasthttp.RequestCtx)
	res := NewResponse(c, log.New("test"))
	res.WriteHeader(http.StatusOK)
	assert.True(t, res.Committed())
	assert.Equal(t, http.StatusOK, res.Status())
}
Пример #9
0
func TestRequest(t *testing.T) {
	ctx := new(fast.RequestCtx)
	url, _ := url.Parse("http://github.com/labstack/echo")
	ctx.Init(&fast.Request{}, fakeAddr{addr: "127.0.0.1"}, nil)
	ctx.Request.Read(bufio.NewReader(bytes.NewBufferString(test.MultipartRequest)))
	ctx.Request.SetRequestURI(url.String())
	test.RequestTest(t, NewRequest(ctx, log.New("echo")))
}
Пример #10
0
func TestResponseSetCookie(t *testing.T) {
	rec := httptest.NewRecorder()
	res := NewResponse(rec, log.New("test"))
	res.SetCookie(&Cookie{&http.Cookie{
		Name:  "name",
		Value: "Jon Snow",
	}})
	assert.Equal(t, "name=Jon Snow", rec.Header().Get("Set-Cookie"))
}
Пример #11
0
func TestResponseWrite(t *testing.T) {
	rec := httptest.NewRecorder()
	res := NewResponse(rec, log.New("test"))
	res.Write([]byte("test"))
	assert.Equal(t, int64(4), res.Size())
	assert.Equal(t, "test", rec.Body.String())
	res.Flush()
	assert.True(t, rec.Flushed)
}
Пример #12
0
func New(templateDir string) tplex.TemplateEx {
	a := &templatePongo2{
		templateDir: templateDir,
		ext:         `.html`,
		Logger:      log.New("tplex"),
	}
	a.templateDir, _ = filepath.Abs(templateDir)
	return a
}
Пример #13
0
func TestEchoLogger(t *testing.T) {
	e := New()
	l := log.New("test")
	e.SetLogger(l)
	assert.Equal(t, l, e.Logger())
	e.SetLogOutput(ioutil.Discard)
	assert.Equal(t, l.Output(), ioutil.Discard)
	e.SetLogLevel(log.OFF)
	assert.Equal(t, l.Level(), log.OFF)
}
Пример #14
0
func TestRequest(t *testing.T) {
	httpReq, _ := http.ReadRequest(bufio.NewReader(strings.NewReader(test.MultipartRequest)))
	url, _ := url.Parse("http://github.com/labstack/echo")
	httpReq.URL = url
	httpReq.RemoteAddr = "127.0.0.1"
	req := NewRequest(httpReq, log.New("echo"))
	test.RequestTest(t, req)
	nr, _ := http.NewRequest("GET", "/", nil)
	req.reset(nr, nil, nil)
	assert.Equal(t, "", req.Host())
}
Пример #15
0
func NewResponseRecorder() *ResponseRecorder {
	rec := httptest.NewRecorder()
	return &ResponseRecorder{
		Response: &Response{
			response: rec,
			header:   &Header{rec.Header()},
			writer:   rec,
			logger:   log.New("test"),
		},
		Body: rec.Body,
	}
}
Пример #16
0
func TestResponseSetCookie(t *testing.T) {
	c := new(fasthttp.RequestCtx)
	res := NewResponse(c, log.New("test"))
	cookie := new(fasthttp.Cookie)
	cookie.SetKey("name")
	cookie.SetValue("Jon Snow")
	res.SetCookie(&Cookie{cookie})
	c.Response.Header.SetCookie(cookie)
	ck := new(fasthttp.Cookie)
	ck.SetKey("name")
	assert.True(t, c.Response.Header.Cookie(ck))
	assert.Equal(t, "Jon Snow", string(ck.Value()))
}
Пример #17
0
// New creates an instance of Echo.
func New() (e *Echo) {
	e = &Echo{maxParam: new(int)}
	e.pool.New = func() interface{} {
		return e.NewContext(nil, nil)
	}
	e.router = NewRouter(e)

	// Defaults
	e.SetHTTPErrorHandler(e.DefaultHTTPErrorHandler)
	e.SetBinder(&binder{})
	e.logger = log.New("echo")
	e.logger.SetLevel(log.ERROR)

	return
}
Пример #18
0
func New(templateDir string) TemplateEx {
	t := &templateEx{
		CachedRelation: make(map[string]*CcRel),
		TemplateDir:    templateDir,
		DelimLeft:      "{{",
		DelimRight:     "}}",
		IncludeTag:     "Include",
		ExtendTag:      "Extend",
		BlockTag:       "Block",
		SuperTag:       "Super",
		Ext:            ".html",
		Debug:          Debug,
	}
	t.Logger = log.New("tplex")
	t.Logger.SetLevel(log.INFO)
	t.InitRegexp()
	return t
}
Пример #19
0
func realMain() int {

	// reads and parses application config params
	config, err := config.ReadFromFile("./config.json")
	if err != nil {
		fmt.Println("Config file reading error. Details: ", err)
		return 1
	}

	// creates Logger (can be replaced with other popular logger)
	log := log.New("GOB ")
	log.Debug("Application launched")

	// creates Backend object
	back, err := backend.New(&config.Backend, log)
	if err != nil {
		log.Error("Backend initialisation error. Details: ", err)
		return 2
	}

	// creates Frontend objects
	front, err := frontend.New(&config.Frontend, log, back)
	if err != nil {
		log.Error("Frontend initialisation error. Details: ", err)
		return 3
	}

	// starts background processes
	if err := back.Start(); err != nil {
		log.Error("Backend processes launching error. Details: ", err)
		return 4
	}

	// starts HTTP listener and handlers
	if err := front.Start(); err != nil {
		log.Error("Frontend listeners/processes error. Details: ", err)
		return 5
	}

	log.Info("Application succesfully terminated")
	return 0
}
Пример #20
0
// WithConfig returns `Server` instance with provided config.
func WithConfig(c engine.Config) (s *Server) {
	s = &Server{
		Server: new(http.Server),
		config: c,
		pool: &pool{
			request: sync.Pool{
				New: func() interface{} {
					return &Request{logger: s.logger}
				},
			},
			response: sync.Pool{
				New: func() interface{} {
					return &Response{logger: s.logger}
				},
			},
			responseAdapter: sync.Pool{
				New: func() interface{} {
					return &responseAdapter{}
				},
			},
			header: sync.Pool{
				New: func() interface{} {
					return &Header{}
				},
			},
			url: sync.Pool{
				New: func() interface{} {
					return &URL{}
				},
			},
		},
		handler: engine.HandlerFunc(func(req engine.Request, res engine.Response) {
			panic("echo: handler not set, use `Server#SetHandler()` to set it.")
		}),
		logger: glog.New("echo"),
	}
	s.ReadTimeout = c.ReadTimeout
	s.WriteTimeout = c.WriteTimeout
	s.Addr = c.Address
	s.Handler = s
	return
}
Пример #21
0
// New creates an instance of Echo.
func New() (e *Echo) {
	e = &Echo{maxParam: new(int)}
	e.pool.New = func() interface{} {
		return NewContext(nil, new(Response), e)
	}
	e.router = NewRouter(e)

	//----------
	// Defaults
	//----------

	e.SetHTTPErrorHandler(e.DefaultHTTPErrorHandler)
	e.SetBinder(&binder{})

	// Logger
	e.logger = log.New("echo")
	e.SetLogLevel(log.FATAL)

	return
}
Пример #22
0
// WithConfig returns `Server` with provided config.
func WithConfig(c engine.Config) (s *Server) {
	s = &Server{
		Server: new(fasthttp.Server),
		config: c,
		pool: &pool{
			request: sync.Pool{
				New: func() interface{} {
					return &Request{logger: s.logger}
				},
			},
			response: sync.Pool{
				New: func() interface{} {
					return &Response{logger: s.logger}
				},
			},
			requestHeader: sync.Pool{
				New: func() interface{} {
					return &RequestHeader{}
				},
			},
			responseHeader: sync.Pool{
				New: func() interface{} {
					return &ResponseHeader{}
				},
			},
			url: sync.Pool{
				New: func() interface{} {
					return &URL{}
				},
			},
		},
		handler: engine.HandlerFunc(func(req engine.Request, res engine.Response) {
			s.logger.Error("handler not set, use `SetHandler()` to set it.")
		}),
		logger: glog.New("echo"),
	}
	s.ReadTimeout = c.ReadTimeout
	s.WriteTimeout = c.WriteTimeout
	s.Handler = s.ServeHTTP
	return
}
Пример #23
0
// New creates an instance of Echo.
func New() (e *Echo) {
	e = &Echo{maxParam: new(int)}
	e.pool.New = func() interface{} {
		return NewContext(nil, nil, e)
	}
	e.router = NewRouter(e)
	e.middleware = []Middleware{e.router}
	e.head = HandlerFunc(func(c Context) error {
		return c.Handle(c)
	})
	e.pristineHead = e.head
	e.chainMiddleware()

	// Defaults
	e.SetHTTPErrorHandler(e.DefaultHTTPErrorHandler)
	e.SetBinder(&binder{})
	e.logger = log.New("echo")
	e.logger.SetLevel(log.ERROR)

	return
}
Пример #24
0
Файл: echo.go Проект: o1egl/echo
// New creates an instance of Echo.
func New() (e *Echo) {
	e = &Echo{
		maxParam: new(int),
		encoders: map[string]Encoder{
			MIMEApplicationJSON:            &jsonEncoder{},
			MIMEApplicationJSONCharsetUTF8: &jsonEncoder{},
			MIMEApplicationXML:             &xmlEncoder{},
			MIMEApplicationXMLCharsetUTF8:  &xmlEncoder{},
		},
	}
	e.pool.New = func() interface{} {
		return e.NewContext(nil, nil)
	}
	e.router = NewRouter(e)

	// Defaults
	e.SetHTTPErrorHandler(e.DefaultHTTPErrorHandler)
	e.SetBinder(&binder{})
	l := glog.New("echo")
	l.SetLevel(glog.ERROR)
	e.SetLogger(l)
	return
}
Пример #25
0
	//----------------
	// Error handlers
	//----------------

	notFoundHandler = func(c *Context) error {
		return NewHTTPError(http.StatusNotFound)
	}

	methodNotAllowedHandler = func(c *Context) error {
		return NewHTTPError(http.StatusMethodNotAllowed)
	}

	unixEpochTime = time.Unix(0, 0)

	logger = log.New("echo")
)

// New creates an instance of Echo.
func New() (e *Echo) {
	e = &Echo{maxParam: new(int)}
	e.pool.New = func() interface{} {
		return NewContext(nil, new(Response), e)
	}
	e.router = NewRouter(e)

	//----------
	// Defaults
	//----------

	e.HTTP2(true)