Skip to content

insionng/vodka

Repository files navigation

Vodka V2+

由于Echo V3不再支持fasthttp, 于是我将以Vodka的名义自行维护Echo V2的后续开发,如果你也在使用我的这个版本欢迎留言交流.

Fast and unfancy HTTP server framework for Go (Golang). Up to 10x faster than the rest.

Feature Overview

  • Optimized HTTP router which smartly prioritize routes
  • Build robust and scalable RESTful APIs
  • Run with standard HTTP server or FastHTTP server
  • Group APIs
  • Extensible middleware framework
  • Define middleware at root, group or route level
  • Data binding for JSON, XML and form payload
  • Handy functions to send variety of HTTP responses
  • Centralized HTTP error handling
  • Template rendering with any template engine
  • Define your format for the logger
  • Highly customizable

Performance

  • Environment:

    • Go 1.7.1
    • wrk 4.2.0
    • Memory 16 GB
    • Processor Intel® Xeon® CPU E3-1231 v3 @ 3.40GHz × 8

    Simple Test:

    package main
    
    import (
        "net/http"
    
        "github.com/insionng/vodka"
        "github.com/insionng/vodka/engine/fasthttp"
    )
    
    func main() {
        v := vodka.New()
        v.GET("/", HelloHandler)
        v.Run(fasthttp.New(":1987"))
    }
    
    func HelloHandler(self vodka.Context) error {
        return self.String(http.StatusOK, "Hello, World!")
    }
    wrk -t8 -c400 -d20s http://localhost:1987
    Running 20s test @ http://localhost:1987
    8 threads and 400 connections
    Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     1.06ms    1.15ms  38.67ms   92.60%
    Req/Sec    54.87k     6.99k   77.05k    75.69%
    8747188 requests in 20.05s, 1.21GB read
    Requests/sec: 436330.95
    Transfer/sec:     61.59MB

快速开始

安装

在安装之前确认你已经安装了Go语言. Go语言安装请访问 install instructions.

Vodka is developed and tested using Go 1.7.x+

$ go get -u github.com/insionng/vodka

Hello, World!

Create server.go

package main

import (
	"net/http"
	"github.com/insionng/vodka"
	"github.com/insionng/vodka/engine/fasthttp"
)

func main() {
	v := vodka.New()
	v.GET("/", func(self vodka.Context) error {
		return self.String(http.StatusOK, "Hello, World!")
	})
	v.Run(fasthttp.New(":1987"))
}

Start server

$ go run server.go

Browse to http://localhost:1987 and you should see Hello, World! on the page.

Routing

v.POST("/users", saveUser)
v.GET("/users/:id", getUser)
v.PUT("/users/:id", updateUser)
v.DELETE("/users/:id", deleteUser)

Path Parameters

func getUser(self vodka.Context) error {
	// User ID from path `users/:id`
	id := self.Param("id")
}

Query Parameters

/show?team=x-men&member=wolverine

func show(c vodka.Context) error {
	// Get team and member from the query string
	team := c.QueryParam("team")
	member := c.QueryParam("member")
}

Form application/x-www-form-urlencoded

POST /save

name value
name Joe Smith
email vodka@yougam.com
func save(c vodka.Context) error {
	// Get name and email
	name := c.FormValue("name")
	email := c.FormValue("email")
}

Form multipart/form-data

POST /save

name value
name Joe Smith
email joe@yougam.com
avatar avatar
func save(c vodka.Context) error {
	// Get name and email
	name := c.FormValue("name")
	email := c.FormValue("email")
	// Get avatar
	avatar, err := c.FormFile("avatar")
	if err != nil {
		return err
	}

	// Source
	src, err := avatar.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	// Destination
	dst, err := os.Create(avatar.Filename)
	if err != nil {
		return err
	}
	defer dst.Close()

	// Copy
	if _, err = io.Copy(dst, src); err != nil {
		return err
	}

	return c.HTML(http.StatusOK, "<b>Thank you!</b>")
}

Handling Request

  • Bind JSON or XML or form payload into Go struct based on Content-Type request header.
  • Render response as JSON or XML with status code.
type User struct {
	Name  string `json:"name" xml:"name" form:"name"`
	Email string `json:"email" xml:"email" form:"email"`
}

e.POST("/users", func(c vodka.Context) error {
	u := new(User)
	if err := c.Bind(u); err != nil {
		return err
	}
	return c.JSON(http.StatusCreated, u)
	// or
	// return c.XML(http.StatusCreated, u)
})

Static Content

Server any file from static directory for path /static/*.

e.Static("/static", "static")

Middleware

// Root level middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// Group level middleware
g := e.Group("/root")
g.Use(middleware.BasicAuth(func(username, password string) bool {
	if username == "joe" && password == "secret" {
		return true
	}
	return false
}))

// Route level middleware
track := func(next vodka.HandlerFunc) vodka.HandlerFunc {
	return func(c vodka.Context) error {
		println("request to /users")
		return next(c)
	}
}
e.GET("/users", func(c vodka.Context) error {
	return c.String(http.StatusOK, "/users")
}, track)

Built-in Middleware

Middleware Description
BodyLimit Limit request body
Logger Log HTTP requests
Recover Recover from panics
Gzip Send gzip HTTP response
BasicAuth HTTP basic authentication
JWTAuth JWT authentication
Secure Protection against attacks
CORS Cross-Origin Resource Sharing
CSRF Cross-Site Request Forgery
Static Serve static files
HTTPSRedirect Redirect HTTP requests to HTTPS
HTTPSWWWRedirect Redirect HTTP requests to WWW HTTPS
WWWRedirect Redirect non WWW requests to WWW
NonWWWRedirect Redirect WWW requests to non WWW
AddTrailingSlash Add trailing slash to the request URI
RemoveTrailingSlash Remove trailing slash from the request URI
MethodOverride Override request method

Third-party Middleware

Middleware Description
vodkaperm Keeping track of users, login states and permissions.
vodkapprof Adapt net/http/pprof to vodka.

Need help?

  • [QQ Group] Vodka/Vodka Web 框架群号 242851426
  • Open an issue

Support Us

  • ⭐ the project
  • 🌎 spread the word
  • Contribute to the project

Contribute

Use issues for everything

  • Report issues
  • Discuss on chat before sending a pull request
  • Suggest new features or enhancements
  • Improve/fix documentation

Vodka System

Community created packages for Vodka

Vodka Case

  • ZenPress - Cms/Blog System(just start-up)

Donation

BTC:1JHtavsBqBNGxpR4eLNwjYL9Vjbyr3Tw6T

License

MIT License

QQ Group

Vodka/Vodka Web 框架群号 242851426

Golang编程(Go/Web/Nosql)群号 245386165

Go语言编程(Golang/Web/Orm)群号 231956113

Xorm & Golang群号 280360085

Golang & Tango & Web群号 369240307

Martini&Macaron 交流群 371440803

About

Vodka是一个强大Go语言中间件式的模块化web框架,是基于Echo二次开发的加强版本

Resources

License

Stars

Watchers

Forks

Packages

No packages published