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) 路由

  • 支持GET\POST\HEAD\OPTIONS\PUT\PATCH\DELETE 这几类请求方法
  • 支持HiJack\WebSocket\ServerFile三类特殊应用
  • 支持Any注册方式,默认兼容GET\POST\HEAD\OPTIONS\PUT\PATCH\DELETE方式
  • 支持通过配置开启默认添加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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,932评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,554评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,894评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,442评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,347评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,899评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,325评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,980评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,196评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,163评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,085评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,826评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,389评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,501评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,753评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,171评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,616评论 2 339

推荐阅读更多精彩内容

  • 转发自:http://shanshanpt.github.io/2016/05/03/go-gin.html gi...
    dncmn阅读 6,003评论 0 1
  • Faygo 框架 Faygo 使用全新架构,是最合适开发API接口的Go Web框架。用户只需定义一个struct...
    Andeya阅读 21,644评论 5 27
  • 学习go也有一段时间了,整理了一下学习go的心得体会。结合一个web框架构建来体会一下。demo地址1 路由以及数...
    熊少年阅读 1,488评论 0 0
  • 2019-01-13 星期日,天气晴 周末时光总是这么短暂,这周末在家打了两天游戏,将段位提高到一个前所未有的高度...
    凉城丶丶旧梦阅读 100评论 0 0
  • 说真的看到简书上的你们都怎么努力,我真的觉得自己特别特别懒散,现在大二了,学习一般般,什么特长也没有,做事情三分钟...
    呆毛怪阅读 250评论 0 0