go常用Web框架简介

常用web框架

  • echo
    高性能,可扩展,极简 go Web 框架。

    中间件多,性能高,REST支持,HTTPS支持,HTTP/2支持,WebSocket支持。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package main

    import (
    "net/http"

    "github.com/labstack/echo"
    )

    func main() {
    e := echo.New()
    e.GET("/", func(c echo.Context) error {
    return c.String(http.StatusOK, "Hello, World!")
    })
    e.Logger.Fatal(e.Start(":1323"))
    }
  • gin
    类martini,高性能 go Web 框架。

    性能高,REST支持,HTTPS支持。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package main

    import "gopkg.in/gin-gonic/gin.v1"

    func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
    c.JSON(200, gin.H{
    "message": "pong",
    })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
    }
  • iris
    最高性能 go Web 框架。

    中间件多,性能高,REST支持。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    package main

    import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
    )

    func main() {
    app := iris.New()
    app.Handle("GET", "/", func(ctx context.Context) {
    ctx.HTML("<b> Hello world! </b>")
    })
    app.Run(iris.Addr(":8080"))
    }
  • revel
    高生产力,全功能 go Web 框架。

    功能完整,MVC构架。

    1
    2
    revel new myapp
    revel run myapp
  • martini
    Martini是一个强大为了编写模块化Web应用而生的GO语言框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    package main

    import "github.com/go-martini/martini"

    func main() {
    m := martini.Classic()
    m.Get("/", func() string {
    return "Hello world!"
    })
    m.Run()
    }
  • go-json-rest
    易于构建RESTful JSON APIs的go Web框架。

    中间件多,REST支持,HTTPS支持,WebSocket支持。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    package main

    import (
    "github.com/ant0ine/go-json-rest/rest"
    "log"
    "net/http"
    )

    func main() {
    api := rest.NewApi()
    api.Use(rest.DefaultDevStack...)
    api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
    w.WriteJson(map[string]string{"Body": "Hello World!"})
    }))
    log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
    }
  • utron
    轻量级MVC的 go Web 框架。

  • macaron
    高生产力 go Web 框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    package main

    import "gopkg.in/macaron.v1"

    func main() {
    m := macaron.Classic()
    m.Get("/", func() string {
    return "Hello world!"
    })
    m.Run()
    }
  • buffalo
    快速的 go Web 开发框架。

    1
    2
    buffalo new coke
    buffalo dev
  • go-tigertonic
    json web 服务开发框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    type MyRequest struct {
    ID string `json:"id"`
    Stuff interface{} `json:"stuff"`
    }

    type MyResponse struct {
    ID string `json:"id"`
    Stuff interface{} `json:"stuff"`
    }

    func myHandler(u *url.URL, h http.Header, *MyRequest) (int, http.Header, *MyResponse, error) {
    return http.StatusOK, nil, &MyResponse{"ID", "STUFF"}, nil
    }

    mux := tigertonic.NewTrieServeMux()
    mux.Handle("POST", "/stuff", tigertonic.Timed(tigertonic.Marshaled(myHandler), "myHandler", nil))
    tigertonic.NewServer(":8000", tigertonic.Logged(mux, nil)).ListenAndServe()
  • faygo
    快速方便的高性能 go Web 开发框架,特别是开发API。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    package main

    import (
    // "mime/multipart"
    "time"
    "github.com/henrylee2cn/faygo"
    )

    type Index struct {
    Id int `param:"<in:path> <required> <desc:ID> <range: 0:10>"`
    Title string `param:"<in:query> <nonzero>"`
    Paragraph []string `param:"<in:query> <name:p> <len: 1:10> <regexp: ^[\\w]*$>"`
    Cookie string `param:"<in:cookie> <name:faygoID>"`
    // Picture *multipart.FileHeader `param:"<in:formData> <name:pic> <maxmb:30>"`
    }

    func (i *Index) Serve(ctx *faygo.Context) error {
    if ctx.CookieParam("faygoID") == "" {
    ctx.SetCookie("faygoID", time.Now().String())
    }
    return ctx.JSON(200, i)
    }

    func main() {
    app := faygo.New("myapp", "0.1")

    // Register the route in a chain style
    app.GET("/index/:id", new(Index))

    // Register the route in a tree style
    // app.Route(
    // app.NewGET("/index/:id", new(Index)),
    // )

    // Start the service
    faygo.Run()
    }
  • tango
    微内核,可插拔,高性能 go Web 开发框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    package main

    import (
    "errors"
    "github.com/lunny/tango"
    )

    type Action struct {
    tango.JSON
    }

    func (Action) Get() interface{} {
    if true {
    return map[string]string{
    "say": "Hello tango!",
    }
    }
    return errors.New("something error")
    }

    func main() {
    t := tango.Classic()
    t.Get("/", new(Action))
    t.Run()
    }
  • traffic
    受 Sinatra 启发的多正则匹配的 go Web 框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    package main

    import (
    "net/http"
    "github.com/pilu/traffic"
    "fmt"
    )

    func rootHandler(w traffic.ResponseWriter, r *traffic.Request) {
    fmt.Fprint(w, "Hello World\n")
    }

    func pageHandler(w traffic.ResponseWriter, r *traffic.Request) {
    params := r.URL.Query()
    fmt.Fprintf(w, "Category ID: %s\n", params.Get("category_id"))
    fmt.Fprintf(w, "Page ID: %s\n", params.Get("id"))
    }

    func main() {
    router := traffic.New()

    // Routes
    router.Get("/", rootHandler)
    router.Get("/categories/:category_id/pages/:id", pageHandler)

    router.Run()
    }
  • rest-layer
    让创建 REST API 更简单的 go Web 框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    package main

    import (
    "log"
    "net/http"

    "github.com/rs/rest-layer-mem"
    "github.com/rs/rest-layer/resource"
    "github.com/rs/rest-layer/rest"
    "github.com/rs/rest-layer/schema"
    )

    var (
    // Define a user resource schema
    user = schema.Schema{
    Description: `The user object`,
    Fields: schema.Fields{
    "id": {
    Required: true,
    // When a field is read-only, on default values or hooks can
    // set their value. The client can't change it.
    ReadOnly: true,
    // This is a field hook called when a new user is created.
    // The schema.NewID hook is a provided hook to generate a
    // unique id when no value is provided.
    OnInit: schema.NewID,
    // The Filterable and Sortable allows usage of filter and sort
    // on this field in requests.
    Filterable: true,
    Sortable: true,
    Validator: &schema.String{
    Regexp: "^[0-9a-v]{20}$",
    },
    },
    "created": {
    Required: true,
    ReadOnly: true,
    Filterable: true,
    Sortable: true,
    OnInit: schema.Now,
    Validator: &schema.Time{},
    },
    "updated": {
    Required: true,
    ReadOnly: true,
    Filterable: true,
    Sortable: true,
    OnInit: schema.Now,
    // The OnUpdate hook is called when the item is edited. Here we use
    // provided Now hook which just return the current time.
    OnUpdate: schema.Now,
    Validator: &schema.Time{},
    },
    // Define a name field as required with a string validator
    "name": {
    Required: true,
    Filterable: true,
    Validator: &schema.String{
    MaxLen: 150,
    },
    },
    },
    }

    // Define a post resource schema
    post = schema.Schema{
    Description: `Represents a blog post`,
    Fields: schema.Fields{
    // schema.*Field are shortcuts for common fields
    // (identical to users' same fields)
    "id": schema.IDField,
    "created": schema.CreatedField,
    "updated": schema.UpdatedField,
    // Define a user field which references the user owning the post.
    // See bellow, the content of this field is enforced by the fact
    // that posts is a sub-resource of users.
    "user": {
    Required: true,
    Filterable: true,
    Validator: &schema.Reference{
    Path: "users",
    },
    },
    "published": {
    Required: true,
    Filterable: true,
    Default: false,
    Validator: &schema.Bool{},
    },
    "title": {
    Required: true,
    Validator: &schema.String{
    MaxLen: 150,
    },
    },
    "body": {
    // Dependency defines that body field can't be changed if
    // the published field is not "false".
    Dependency: schema.Q(`{"published": false}`),
    Validator: &schema.String{
    MaxLen: 100000,
    },
    },
    },
    }
    )

    func main() {
    // Create a REST API resource index
    index := resource.NewIndex()

    // Add a resource on /users[/:user_id]
    users := index.Bind("users", user, mem.NewHandler(), resource.Conf{
    // We allow all REST methods
    // (rest.ReadWrite is a shortcut for []resource.Mode{resource.Create,
    // resource.Read, resource.Update, resource.Delete, resource,List})
    AllowedModes: resource.ReadWrite,
    })

    // Bind a sub resource on /users/:user_id/posts[/:post_id]
    // and reference the user on each post using the "user" field of the posts resource.
    users.Bind("posts", "user", post, mem.NewHandler(), resource.Conf{
    // Posts can only be read, created and deleted, not updated
    AllowedModes: []resource.Mode{resource.Read, resource.List,
    resource.Create, resource.Delete},
    })

    // Create API HTTP handler for the resource graph
    api, err := rest.NewHandler(index)
    if err != nil {
    log.Fatalf("Invalid API configuration: %s", err)
    }

    // Bind the API under /api/ path
    http.Handle("/api/", http.StripPrefix("/api/", api))

    // Serve it
    log.Print("Serving API on http://localhost:8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
    log.Fatal(err)
    }
    }
  • gongular
    让开发 API 简单的 go Web 框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    type WelcomeMessage struct {
    Message string
    Date time.Time
    }

    g := gongular.NewRouter()
    g.GET("/", func(c *gongular.Context) WelcomeMessage {
    return WelcomeMessage{
    Message: "Hello, you are coming from: " + c.Request().RemoteAddr,
    Date: time.Now(),
    }
    })
  • lessgo
    简单、稳定、高效、灵活的 go Web 开发框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import (
    "github.com/henrylee2cn/lessgo"
    "github.com/henrylee2cn/lessgoext/swagger"

    _ "github.com/henrylee2cn/lessgoext/dbservice/xorm"
    // _ "github.com/henrylee2cn/lessgoext/dbservice/gorm"

    _ "github.com/henrylee2cn/lessgo_demo/middleware"
    _ "github.com/henrylee2cn/lessgo_demo/router"
    )

    func main() {
    // 开启自动api文档,通过config/apidoc_allow.myconfig进行配置
    swagger.Reg()
    // 指定根目录URL
    lessgo.SetHome("/home")
    // 开启网络服务
    lessgo.Run()
    }
  • neo
    极其简单,快速,微内核的 go Web 框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package main

    import (
    "github.com/ivpusic/neo"
    )

    func main() {
    app := neo.App()

    app.Get("/", func(ctx *neo.Ctx) (int, error) {
    return 200, ctx.Res.Text("I am Neo Programmer")
    })

    app.Start()
    }
  • gondola
    快速开发 go Web 框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    package main

    import (
    "gnd.la/app"
    "gnd.la/config"
    )

    var (
    App *app.App
    )

    func init() {
    config.MustParse()
    App = app.New()
    App.HandleNamed("^/$", MainHandler, "main")
    }
  • golf
    快速简单高性能轻量的 go Web 开发框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package main

    import "github.com/dinever/golf"

    func mainHandler(ctx *golf.Context) {
    ctx.Send("Hello World!")
    }

    func pageHandler(ctx *golf.Context) {
    ctx.Send("Page: " + ctx.Param("page"))
    }

    func main() {
    app := golf.New()
    app.Get("/", mainHandler)
    app.Get("/p/:page/", pageHandler)
    app.Run(":9000")
    }
  • go-relax
    专为 RESTful API 开发的 go Web 框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package main

    import (
    "github.com/codehack/go-relax"
    )

    type Hello string

    func (h *Hello) Index(ctx *relax.Context) {
    ctx.Respond(h)
    }

    func main() {
    h := Hello("hello world!")
    svc := relax.NewService("http://api.company.com/")
    svc.Resource(&h)
    svc.Run()
    }
  • gem
    高性能,易用,REST支持,HTTP/2支持的 go Web 框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    package main

    import (
    "log"

    "github.com/go-gem/gem"
    )

    func index(ctx *gem.Context) {
    ctx.HTML(200, "hello world")
    }

    func main() {
    // Create server.
    srv := gem.New(":8080")

    // Create router.
    router := gem.NewRouter()
    // Register handler
    router.GET("/", index)

    // Start server.
    log.Println(srv.ListenAndServe(router.Handler()))
    }
  • goat
    极简JSON API go Web 框架,REST支持。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    package main

    import (
    "net/http"

    "github.com/bahlo/goat"
    )

    func helloHandler(w http.ResponseWriter, r *http.Request, p goat.Params) {
    goat.WriteJSON(w, map[string]string{
    "hello": p["name"],
    })
    }

    func main() {
    r := goat.New()

    r.Get("/hello/:name", "hello_url", helloHandler)

    r.Run(":8080")
    }
  • rex
    现在化 go Web 开发框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    package main

    import (
    "io"
    "net/http"

    "github.com/goanywhere/rex"
    )

    func main() {
    app := rex.New()
    app.Get("/", func(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello World")
    })
    app.Run()
    }
  • air
    一个理想的 RESTful API go Web 开发框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package main

    import "github.com/sheng/air"

    func main() {
    a := air.New()
    a.GET("/", homeHandler)
    a.Serve()
    }

    func homeHandler(c *air.Context) error {
    return c.String("Hello, 世界")
    }
  • yarf
    又一个 高性能 REST 开发框架。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    package main

    import (
    "github.com/yarf-framework/yarf"
    )

    // Define a simple resource
    type Hello struct {
    yarf.Resource
    }

    // Implement the GET method
    func (h *Hello) Get(c *yarf.Context) error {
    c.Render("Hello world!")

    return nil
    }

    // Run app server on http://localhost:8080
    func main() {
    y := yarf.New()

    y.Add("/", new(Hello))

    y.Start(":8080")
    }

适合开发 REST API 的框架

  • github收藏较多的框架
    • echo
    • gin
    • iris
    • go-json-rest
    • martini
    • macaron
  • 小众但可能好用的框架
    • tango
    • neo
    • go-relax
    • gem
    • goat
    • air
    • yarf
    • faygo
    • traffic
    • rest-layer
    • gongular
    • lessgo
    • go-tigertonic