go web框架 - Go语言中文社区

go web框架


可能根据项目不同可以选下面不同框架,里面具体的没有对对比,如果想深入了解或学习可以在之后再深入,这里提供简单的引入,废话不多少,上代码:
1、Martini
Martini框架是使用Go语言作为开发语言的一个强力的快速构建模块化web应用与服务的开发框架。Martini是一个专门用来处理Web相关内容的框架,其并没有自带有关ORM或详细的分层内容。所以当我们使用Martini作为我们的开发框架时,我们还需要选取适合的ORM等其他包。

package main

import (
    "github.com/astaxie/beego/context"
    "github.com/go-martini/martini"
    "github.com/martini-contrib/render"
    "net/http"
    "fmt"
)

//定义一个自己的中间件,这里将beego的context注入
func myContext() martini.Handler {
    return func(res http.ResponseWriter, req *http.Request, c martini.Context) {
        ctx := context.Context{Request: req, ResponseWriter: res}
        ctx.Input = context.NewInput(req)
        ctx.Output = context.NewOutput()
        c.Map(ctx)
    }
}

func main() {
    m := martini.Classic()
    m.Use(render.Renderer()) //注入中间件(渲染JSON和HTML模板的处理器中间件)
    m.Use(myContext())       //注入自己写的中间件

    m.Use(func(c martini.Context) {
        fmt.Println("before a request")
        c.Next() //Next方法之后最后处理
        fmt.Println("after a request")
    })

    //普通的GET方式路由
    m.Get("/", func() string {
        return "hello world!"
    })

    //路由分组
    m.Group("/books", func(r martini.Router) {
        r.Get("/list", getBooks)
        r.Post("/add", getBooks)
        r.Delete("/delete", getBooks)
    })

    //我们以中间件的方式来注入一个Handler
    m.Use(MyHeader(m))

    m.RunOnAddr(":8080") //运行程序监听端口
}

func getBooks() string {
    return "books"
}

//中间件Handler
func MyHeader(m *martini.ClassicMartini) martini.Handler {
    return func() {
        m.Group("/app", func(r martini.Router) {
            my := new(App)
            r.Get("/index", my.Index)
            r.Get("/test/:aa", my.Test)
        })
    }
}

//应用的处理
type App struct{}

func (this *App) Index(r render.Render, ctx context.Context) {
    fmt.Println(ctx.Input.Query("action"))
    ctx.WriteString("你好世界")
}

func (this *App) Test(r render.Render, params martini.Params, req *http.Request) {
    fmt.Println(params)

    parm := make(map[string]interface{})
    if t, ok := params["aa"]; ok {
        parm["aa"] = t
    }
    req.ParseForm()
    fmt.Println(parm, req.Form)

    r.Text(200, "----")
}

参考:(1)https://github.com/go-martini/martini/blob/master/translations/README_zh_cn.md
(2)https://studygolang.com/articles/5196

2、dotweb
github地址:https://github.com/devfeel/dotweb

(1)安装
> $ go get -u github.com/devfeel/dotweb

(2) 简单实践:

package main
import (
    "fmt"
    "github.com/devfeel/dotweb"
)
const port = 8080
// Res struct
type Res struct {
    Result string `json:"result"`
    Data   string `json:"data"`
    Name   string `json:"name"`
}
//测试dotweb这个框架
func main() {
    app := dotweb.New() //初始化dotweb server
    app.SetLogPath("/user/local/")
    //设置路由
    InitRouter(app.HttpServer)
    err := app.StartServer(port)
    if err != nil {
        fmt.Println("dotweb startServer is err, err message is:", err)
        return
    }
    fmt.Println("成功接收")
}
//InitRouter func
func InitRouter(server *dotweb.HttpServer) {
    server.Router().GET("/push", Index)
}

//Index func
func Index(server *dotweb.HttpContext) {
    name := server.FormValue("name")
    if name == "" {
        fmt.Println("获取name字段为nil")
        return
    }
    server.WriteJson(&Res{
        Result: "success",
        Data:   "成功",
    })
}

其他例子可以参考:https://github.com/devfeel/dotweb-example

(3)Feature

  • 支持静态路由、参数路由、组路由
  • 路由支持文件/目录服务,支持设置是否允许目录浏览
  • HttpModule支持,支持路由之前全局级别的自定义代码能力
  • 中间件支持,支持App、Group、Router级别的设置 - https://github.com/devfeel/middleware
  • Feature支持,可绑定HttpServer全局启用
  • 支持STRING/JSON/JSONP/HTML格式输出
  • 集成Mock能力
  • 集成Timeout Hook
  • 全局HTTP错误处理
  • 全局日志处理
  • 支持Hijack与websocket
  • 内建Cache支持
  • 内建Session支持 - 支持主备redis自动切换
  • 内建TLS支持
  • 支持接入第三方模板引擎(需实现dotweb.Renderer接口)
  • 模块可配置
  • 自集成基础统计数据,并支持按分钟为单位的间隔时间统计数据输出
    (4)配置例子
  • dotweb.conf
     <?xml version="1.0" encoding="UTF-8"?>
<config>
<app logpath="d:/gotmp/" enabledlog="true" runmode="development"/>
<server isrun="true" indexpage="index.html" port="8080" enabledgzip="false" enabledlistdir="false" enabledautohead="true" requesttimeout="30000"/>
<session enabled="true" mode="runtime" timeout="20" />
<appset>
    <set key="set1" value="1" />
    <set key="set2" value="2" />
    <set key="set3" value="3" />
    <set key="set4" value="4" />
</appset>
<middlewares>
    <middleware name="applog" isuse="true" />
</middlewares>
<routers>
    <router method="GET" path="/index" handler="Index" isuse="true">
         <middleware name="urllog" isuse="true" />
    </router>
    <router method="GET" path="/index2" handler="Index" isuse="true">
        <middleware name="urllog" isuse="true" />
    </router>
    <router method="GET" path="/index3" handler="Index" isuse="true">
            <middleware name="urllog" isuse="true" />
    </router>
    <router method="GET" path="/redirect" handler="Redirect" isuse="true"></router>
    <router method="GET" path="/error" handler="Error" isuse="true"></router>
    <router method="GET" path="/panic" handler="Panic" isuse="true"></router>
    <router method="GET" path="/appset" handler="appset" isuse="true"></router>
</routers>
<groups>
    <group path="/admin" isuse="true">
        <middleware name="grouplog" isuse="true" />
        <middleware name="simpleauth" isuse="true" />
        <router method="GET" path="/login" handler="Login" isuse="true">
            <middleware name="urllog" isuse="true" />
        </router>
        <router method="GET" path="/login3" handler="Login" isuse="true"></router>
        <router method="GET" path="/logout" handler="Logout" isuse="true"></router>
        <router method="GET" path="/login2" handler="Login" isuse="true"></router>
    </group>
</groups>
</config> 
      {
    "App": {
        "LogPath": "d:/gotmp/",
        "EnabledLog": true,
        "RunMode": "development",
        "PProfPort": 0,
        "EnabledPProf": false
    },
    "AppSets": [{
        "Key": "set1",
        "Value": "1"
    }, {
        "Key": "set2",
        "Value": "2"
    }, {
        "Key": "set3",
        "Value": "3"
    }, {
        "Key": "set4",
        "Value": "4"
    }],
    "Offline": {
        "Offline": false,
        "OfflineText": "",
        "OfflineUrl": ""
    },
    "Server": {
        "EnabledListDir": false,
        "EnabledRequestID": false,
        "EnabledGzip": false,
        "EnabledAutoHEAD": true,
        "EnabledAutoCORS": false,
        "EnabledIgnoreFavicon": false,
        "EnabledBindUseJsonTag": false,
        "Port": 8080,
        "EnabledTLS": false,
        "TLSCertFile": "",
        "TLSKeyFile": "",
        "IndexPage": "index.html",
        "EnabledDetailRequestData": false
    },
    "Session": {
        "EnabledSession": true,
        "SessionMode": "runtime",
        "Timeout": 20,
        "ServerIP": "",
        "UserName": "",
        "Password": ""
    },
    "Routers": [{
        "Method": "GET",
        "Path": "/index",
        "HandlerName": "Index",
        "Middlewares": [{
            "Name": "urllog",
            "IsUse": true
        }],
        "IsUse": true
    }, {
        "Method": "GET",
        "Path": "/index2",
        "HandlerName": "Index",
        "Middlewares": [{
            "Name": "urllog",
            "IsUse": true
        }],
        "IsUse": true
    }, {
        "Method": "GET",
        "Path": "/index3",
        "HandlerName": "Index",
        "Middlewares": [{
            "Name": "urllog",
            "IsUse": true
        }],
        "IsUse": true
    }, {
        "Method": "GET",
        "Path": "/redirect",
        "HandlerName": "Redirect",
        "Middlewares": null,
        "IsUse": true
    }, {
        "Method": "GET",
        "Path": "/error",
        "HandlerName": "Error",
        "Middlewares": null,
        "IsUse": true
    }, {
        "Method": "GET",
        "Path": "/panic",
        "HandlerName": "Panic",
        "Middlewares": null,
        "IsUse": true
    }, {
        "Method": "GET",
        "Path": "/appset",
        "HandlerName": "appset",
        "Middlewares": null,
        "IsUse": true
    }],
    "Groups": [{
        "Path": "/admin",
        "Routers": [{
            "Method": "GET",
            "Path": "/login",
            "HandlerName": "Login",
            "Middlewares": [{
                "Name": "urllog",
                "IsUse": true
            }],
            "IsUse": true
        }, {
            "Method": "GET",
            "Path": "/login3",
            "HandlerName": "Login",
            "Middlewares": null,
            "IsUse": true
        }, {
            "Method": "GET",
            "Path": "/logout",
            "HandlerName": "Logout",
            "Middlewares": null,
            "IsUse": true
        }, {
            "Method": "GET",
            "Path": "/login2",
            "HandlerName": "Login",
            "Middlewares": null,
            "IsUse": true
        }],
        "Middlewares": [{
            "Name": "grouplog",
            "IsUse": true
        }, {
            "Name": "simpleauth",
            "IsUse": true
        }],
        "IsUse": true
    }],
    "Middlewares": [{
        "Name": "applog",
        "IsUse": true
    }]
}

(5) 路由

  • 支持GETPOSTHEADOPTIONSPUTPATCHDELETE 这几类请求方法
  • 支持HiJackWebSocketServerFile三类特殊应用
  • 支持Any注册方式,默认兼容GETPOSTHEADOPTIONSPUTPATCHDELETE方式
  • 支持通过配置开启默认添加HEAD方式
  • 支持注册Handler,以启用配置化
  • 支持检查请求与指定路由是否匹配
    (6)其他可以借鉴这里:https://www.ctolib.com/dotweb.html

3、gin框架
Gin是一个golang的微框架,封装比较优雅,API友好,源码注释比较明确,已经发布了1.0版本。具有快速灵活,容错方便等特点。其实对于golang而言,web框架的依赖要远比Python,Java之类的要小。自身的net/http足够简单,性能也非常不错。框架更像是一些常用函数或者工具的集合。借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范。
下面就Gin的用法做一个简单的介绍。
首先需要安装,安装比较简单,使用go get即可:

$ go get gopkg.in/gin-gonic/gin.v1

gin的版本托管再 gopkg的网站上。我在安装的过程中,gokpg卡住了,后来不得不根据gin里的godep的文件,把响应的源码从github上下载,然后copy到对应的目录。

package main
import (
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
)

func main(){

    router := gin.Default()

    router.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Hello World")
    })
    router.Run(":8000")
}

简单几行代码,就能实现一个web服务。使用gin的Default方法创建一个路由handler。然后通过HTTP方法绑定路由规则和路由函数。不同于net/http库的路由函数,gin进行了封装,把request和response都封装到gin.Context的上下文环境。最后是启动路由的Run方法监听端口。麻雀虽小,五脏俱全。当然,除了GET方法,gin也支持POST,PUT,DELETE,OPTION等常用的restful方法。

restful路由,gin的路由来自httprouter库。因此httprouter具有的功能,gin也具有,不过gin不支持路由正则表达式:

func main(){
    router := gin.Default()

    router.GET("/user/:name", func(c *gin.Context) {
        name := c.Param("name")
        c.String(http.StatusOK, "Hello %s", name)
    })
}

冒号:加上一个参数名组成路由参数。可以使用c.Params的方法读取其值。当然这个值是字串string。诸如/user/rsj217,和/user/hello都可以匹配,而/user/和/user/rsj217/不会被匹配。除了:,gin还提供了号处理参数,号能匹配的规则就更多。

func main(){
    router := gin.Default()

    router.GET("/user/:name/*action", func(c *gin.Context) {
        name := c.Param("name")
        action := c.Param("action")
        message := name + " is " + action
        c.String(http.StatusOK, message)
    })
}

参考:https://studygolang.com/articles/11819?fr=sidebar

4、iris
(1) github地址https://github.com/kataras/iris

(2) 文档https://docs.iris-go.com/

(3) 安装

$ go get -u github.com/kataras/iris

(4)简单的Hello world

package main

   import "github.com/kataras/iris"

   func main() {
     app := iris.Default()

     // Method:   GET
     // Resource: http://localhost:8080/
     app.Handle("GET", "/", func(ctx iris.Context) {
       ctx.HTML("Hello world!")
     })

     // same as app.Handle("GET", "/ping", [...])
     // Method:   GET
     // Resource: http://localhost:8080/ping
     app.Get("/ping", func(ctx iris.Context) {
       ctx.WriteString("pong")
     })

     // Method:   GET
     // Resource: http://localhost:8080/hello
     app.Get("/hello", func(ctx iris.Context) {
       ctx.JSON(iris.Map{"message": "Hello iris web framework."})
     })

     // http://localhost:8080
     // http://localhost:8080/ping
     // http://localhost:8080/hello
     app.Run(iris.Addr(":8080"))
   }

(5)运行
> $ go run main.go
新打开个窗口执行
curl http://localhost:8080
结果 Hello world!
或在浏览器 访问http://localhost:8080

原文:https://blog.csdn.net/guyan0319/article/details/80625913

5、echo
(1)安装

$ go get github.com/labstack/echo/...
(2) 编写Hello World

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"))
}

启动服务

$ go run server.go
用在浏览器访问 http://localhost:1323 然后你就能在页面上看到 Hello, World!

(3) 路由
e.POST("/users", saveUser)
e.GET("/users/:id", getUser)
e.PUT("/users/:id", updateUser)
e.DELETE("/users/:id", deleteUser)

其他操作可以参考:http://go-echo.org
原文:http://go-echo.org

版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/ef246ba28b6e
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-12 12:04:05
  • 阅读 ( 982 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢