High performance, simple Go web framework

Overview

Elton

license Build Status

Elton的实现参考了koa以及echo,中间件的调整均为洋葱模型:请求由外至内,响应由内至外。主要特性如下:

  • 处理函数(中间件)均以返回error的形式响应出错,方便使用统一的出错处理中间件将出错统一转换为对应的输出(JSON),并根据出错的类型等生成各类统计分析
  • 成功响应数据直接赋值至Context.Body(interface{}),由统一的响应中间件将其转换为对应的输出(JSON,XML)

Hello, World!

下面我们来演示如何使用elton返回Hello, World!,并且添加了一些常用的中间件。

package main

import (
	"github.com/vicanso/elton"
	"github.com/vicanso/elton/middleware"
)

func main() {
	e := elton.New()

	// panic处理
	e.Use(middleware.NewRecover())

	// 出错处理
	e.Use(middleware.NewDefaultError())

	// 默认的请求数据解析
	e.Use(middleware.NewDefaultBodyParser())

	// not modified 304的处理
	e.Use(middleware.NewDefaultFresh())
	e.Use(middleware.NewDefaultETag())

	// 响应数据转换为json
	e.Use(middleware.NewDefaultResponder())

	e.GET("/", func(c *elton.Context) error {
		c.Body = &struct {
			Message string `json:"message,omitempty"`
		}{
			"Hello, World!",
		}
		return nil
	})

	e.GET("/books/{id}", func(c *elton.Context) error {
		c.Body = &struct {
			ID string `json:"id,omitempty"`
		}{
			c.Param("id"),
		}
		return nil
	})

	e.POST("/login", func(c *elton.Context) error {
		c.SetContentTypeByExt(".json")
		c.Body = c.RequestBody
		return nil
	})

	err := e.ListenAndServe(":3000")
	if err != nil {
		panic(err)
	}
}
go run main.go

之后在浏览器中打开http://localhost:3000/则能看到返回的Hello, World!

路由

elton每个路由可以添加多个中间件处理函数,根据路由与及HTTP请求方法指定不同的路由处理函数。而全局的中间件则可通过Use方法来添加。

e.Use(...func(*elton.Context) error)
e.Method(path string, ...func(*elton.Context) error)
  • eelton实例化对象
  • Method 为HTTP的请求方法,如:GET, PUT, POST等等
  • path 为HTTP路由路径
  • func(*elton.Context) error 为路由处理函数(中间件),当匹配的路由被请求时,对应的处理函数则会被调用

路由示例

elton的路由使用chi的路由简化而来,下面是两个简单的示例。

// 带参数路由
e.GET("/users/{type}", func(c *elton.Context) error {
	c.BodyBuffer = bytes.NewBufferString(c.Param("type"))
	return nil
})

// 复合参数
e.GET("/books/{category:[a-z-]+}-{type}", func(c *elton.Context) error {
	c.BodyBuffer = bytes.NewBufferString(c.Param("category") + c.Param("type"))
	return nil
})

// 带中间件的路由配置
e.GET("/users/me", func(c *elton.Context) error {
	c.Set("account", "tree.xie")
	return c.Next()
}, func(c *elton.Context) error {
	c.BodyBuffer = bytes.NewBufferString(c.GetString("account"))
	return nil
})

中间件

简单方便的中间件机制,依赖各类定制的中间件,通过各类中间件的组合,方便快捷实现各类HTTP服务,简单介绍数据响应与出错处理的中间件。

responder

HTTP请求响应数据时,需要将数据转换为Buffer返回,而在应用时响应数据一般为各类的struct或map等结构化数据,因此elton提供了Body(interface{})字段来保存这些数据,再使用自定义的中间件将数据转换为对应的字节数据,elton-responder提供了将struct(map)转换为json字节并设置对应的Content-Type,对于string([]byte)则直接输出。

package main

import (
	"github.com/vicanso/elton"
	"github.com/vicanso/elton/middleware"
)

func main() {

	e := elton.New()
	// 对响应数据 c.Body 转换为相应的json响应
	e.Use(middleware.NewDefaultResponder())

	getSession := func(c *elton.Context) error {
		c.Set("account", "tree.xie")
		return c.Next()
	}
	e.GET("/users/me", getSession, func(c *elton.Context) (err error) {
		c.Body = &struct {
			Name string `json:"name"`
			Type string `json:"type"`
		}{
			c.GetString("account"),
			"vip",
		}
		return
	})

	err := e.ListenAndServe(":3000")
	if err != nil {
		panic(err)
	}
}

error

当请求处理失败时,直接返回error则可,elton从error中获取出错信息并输出。默认的出错处理并不适合实际应用场景,建议使用自定义出错类配合中间件,便于统一的错误处理,程序监控,下面是引入错误中间件将出错转换为json形式的响应。

package main

import (
	"github.com/vicanso/elton"
	"github.com/vicanso/elton/middleware"
	"github.com/vicanso/hes"
)

func main() {

	e := elton.New()
	// 指定出错以json的形式返回
	e.Use(middleware.NewError(middleware.ErrorConfig{
		ResponseType: "json",
	}))

	e.GET("/", func(c *elton.Context) (err error) {
		err = &hes.Error{
			StatusCode: 400,
			Category:   "users",
			Message:    "出错啦",
		}
		return
	})

	err := e.ListenAndServe(":3000")
	if err != nil {
		panic(err)
	}
}

更多的中间件可以参考middlewares

bench

goos: darwin
goarch: amd64
pkg: github.com/vicanso/elton
BenchmarkRoutes-8                        5569852               214 ns/op             152 B/op          3 allocs/op
BenchmarkGetFunctionName-8              124616256                9.61 ns/op            0 B/op          0 allocs/op
BenchmarkContextGet-8                   13823508                84.1 ns/op            16 B/op          1 allocs/op
BenchmarkContextNewMap-8                157319816                7.60 ns/op            0 B/op          0 allocs/op
BenchmarkConvertServerTiming-8           1339969              1059 ns/op             360 B/op         11 allocs/op
BenchmarkGetStatus-8                    1000000000               0.282 ns/op           0 B/op          0 allocs/op
BenchmarkStatic-8                          20527             56061 ns/op           25975 B/op        628 allocs/op
BenchmarkGitHubAPI-8                       13024             92207 ns/op           33829 B/op        812 allocs/op
BenchmarkGplusAPI-8                       260158              4349 ns/op            2147 B/op         52 allocs/op
BenchmarkParseAPI-8                       135792              8433 ns/op            4288 B/op        104 allocs/op
BenchmarkRWMutexSignedKeys-8            75854030                15.9 ns/op             0 B/op          0 allocs/op
BenchmarkAtomicSignedKeys-8             833694663                1.43 ns/op            0 B/op          0 allocs/op
PASS
ok      github.com/vicanso/elton        19.403s
goos: darwin
goarch: amd64
pkg: github.com/vicanso/elton/middleware
BenchmarkGenETag-8        244416              4521 ns/op             280 B/op          7 allocs/op
BenchmarkMd5-8            196239              6011 ns/op             232 B/op          7 allocs/op
BenchmarkProxy-8           14181             76270 ns/op           15840 B/op        105 allocs/op
PASS
ok      github.com/vicanso/elton/middleware     5.429s
You might also like...
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Golanger Web Framework is a lightweight framework for writing web applications in Go.

/* Copyright 2013 Golanger.com. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except

The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework.

jin About The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework. If thi

Tigo is an HTTP web framework written in Go (Golang).It features a Tornado-like API with better performance.  Tigo是一款用Go语言开发的web应用框架,API特性类似于Tornado并且拥有比Tornado更好的性能。
Tigo is an HTTP web framework written in Go (Golang).It features a Tornado-like API with better performance. Tigo是一款用Go语言开发的web应用框架,API特性类似于Tornado并且拥有比Tornado更好的性能。

Tigo(For English Documentation Click Here) 一个使用Go语言开发的web框架。 相关工具及插件 tiger tiger是一个专门为Tigo框架量身定做的脚手架工具,可以使用tiger新建Tigo项目或者执行其他操作。

Package macaron is a high productive and modular web framework in Go.
Package macaron is a high productive and modular web framework in Go.

Macaron Package macaron is a high productive and modular web framework in Go. Getting Started The minimum requirement of Go is 1.6. To install Macaron

A high productivity, full-stack web framework for the Go language.

Revel Framework A high productivity, full-stack web framework for the Go language. Current Version: 1.0.0 (2020-07-11) Supports go.mod package managem

Goal is a toolkit for high productivity web development in Go language in the spirit of Revel Framework that is built around the concept of code generation.

Goal Goal is a set of tools for high productivity web development in Go language. Goal, being mostly inspired by Revel Framework and its discussions,

A high level web-framework for Go

go-start is a high level web-framework for Go, like Django for Python or Rails for Ruby. Installation: go get github.com/ungerik/go-start Documentatio

⚡ Rux is an simple and fast web framework. support middleware, compatible http.Handler interface. 简单且快速的 Go web 框架,支持中间件,兼容 http.Handler 接口

Rux Simple and fast web framework for build golang HTTP applications. NOTICE: v1.3.x is not fully compatible with v1.2.x version Fast route match, sup

Comments
  • RequestBody is empty when submit multipart/form-data

    RequestBody is empty when submit multipart/form-data

    package main
    
    import (
    	"fmt"
    	"github.com/vicanso/elton"
    	"github.com/vicanso/elton/middleware"
    )
    
    func main() {
    	e := elton.New()
    	e.Use(middleware.NewDefaultResponder())   
    	e.Use(middleware.NewDefaultBodyParser())
    
    	e.GET("/form", func(c *elton.Context) error {
    		c.Header().Set("Content-Type", "text/html")
    		c.Body = `<html><head><meta charset='utf-8'/></head><body>
    <form action="/upload", method="post" enctype="multipart/form-data">
    <input type="file" name="upfile">
    <input type="submit" />
    </form></body></html>`
    
    		return nil
    	})
    
    	e.POST("/upload", func(c *elton.Context) error {
    
    		fmt.Println(string(c.RequestBody))
    
    		c.Body = c.RequestBody
    		return nil
    	})
    
    	err := e.ListenAndServe(":3000")
    	if err != nil {
    		panic(err)
    	}
    }
    
    
    opened by tablecell 5
  • 同学,您这个项目引入了14个开源组件,存在2个漏洞,辛苦升级一下

    同学,您这个项目引入了14个开源组件,存在2个漏洞,辛苦升级一下

    检测到 vicanso/elton 一共引入了14个开源组件,存在2个漏洞

    漏洞标题:go-yaml < 2.2.8拒绝服务漏洞
    缺陷组件:gopkg.in/[email protected]
    漏洞编号:CVE-2019-11254
    漏洞描述:gopkg.in/yaml.v2是go语言中用于处理yaml格式的包。
    在2.2.8之前的版本中,处理恶意的yaml数据时,会导致CPU资源耗尽。
    漏洞由Kubernetes开发者在fuzz测试中发现并提交修复补丁。
    国家漏洞库信息:https://www.cnvd.org.cn/flaw/show/CNVD-2020-35519
    影响范围:(∞, 2.2.8)
    最小修复版本:2.2.8
    缺陷组件引入路径:github.com/vicanso/[email protected]>gopkg.in/[email protected]
    

    另外还有2个漏洞,详细报告:https://mofeisec.com/jr?p=aaf548

    opened by ghost 0
Releases(v1.9.5)
Owner
Tree Xie
Do something or nothing
Tree Xie
beego is an open-source, high-performance web framework for the Go programming language.

Beego Beego is used for rapid development of enterprise application in Go, including RESTful APIs, web apps and backend services. It is inspired by To

astaxie 568 Nov 18, 2022
High performance, minimalist Go web framework

Supported Go versions As of version 4.0.0, Echo is available as a Go module. Therefore a Go version capable of understanding /vN suffixed imports is r

LabStack LLC 24.2k Nov 20, 2022
Gearbox :gear: is a web framework written in Go with a focus on high performance

gearbox ⚙️ is a web framework for building micro services written in Go with a focus on high performance. It's built on fasthttp which is up to 10x fa

Gearbox 687 Nov 12, 2022
hiboot is a high performance web and cli application framework with dependency injection support

Hiboot - web/cli application framework About Hiboot is a cloud native web and cli application framework written in Go. Hiboot is not trying to reinven

hidevops.io 179 Nov 20, 2022
Gearbox :gear: is a web framework written in Go with a focus on high performance

gearbox ⚙️ is a web framework for building micro services written in Go with a focus on high performance. It's built on fasthttp which is up to 10x fa

Gearbox 688 Nov 28, 2022
beego is an open-source, high-performance web framework for the Go programming language.

Beego Beego is used for rapid development of enterprise application in Go, including RESTful APIs, web apps and backend services. It is inspired by To

beego Framework 29.1k Nov 18, 2022
letgo is an open-source, high-performance web framework for the Go programming language.

high-performance Lightweight web framework for the Go programming language. golang web framework,高可用golang web框架,go语言 web框架 ,go web

wjp 350 Sep 23, 2022
Dragon 🐲 🐲 🐲 is an enterprise high performance web framework with Go for the feature and comfortable develop.

Dragon start dragon ab performance Dragon ?? ?? ?? is a lightweight high performance web framework with Go for the feature and comfortable develop. 中文

dragon 8 Sep 14, 2022
Dragon 🐲 🐲 🐲 is a lightweight high performance web framework with Go for the feature and comfortable develop.

Dragon project new link start dragon ab performance Dragon ?? ?? ?? is a lightweight high performance web framework with Go for the feature and comfor

azerothyang 0 Sep 6, 2022
GoFrame is a modular, powerful, high-performance and enterprise-class application development framework of Golang.

GoFrame English | 简体中文 GoFrame is a modular, powerful, high-performance and enterprise-class application development framework of Golang. If you're a

GoFrame 8.5k Nov 20, 2022