go post json 多维_Go实战--使用echo和MySQL搭建api

生命不止,继续 go go go!!!

前面有几篇博客跟大家分享了一个golang的框架iris:
Go实战–也许最快的Go语言Web框架kataras/iris初识四(i18n、filelogger、recaptcha)

Go实战–也许最快的Go语言Web框架kataras/iris初识三(Redis、leveldb、BoltDB)

Go实战–也许最快的Go语言Web框架kataras/iris初识二(TOML、Cache、Cookie)

Go实战–也许最快的Go语言Web框架kataras/iris初识(basic认证、Markdown、YAML、Json)

今天就跟大家介绍另一个golang的优秀的框架echo,今天作为开篇就写一个简单的Web应用吧。

echo

High performance, extensible, minimalist Go web framework

特性:
Optimized HTTP router which smartly prioritize routes
Build robust and scalable RESTful APIs
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
Automatic TLS via Let’s Encrypt
HTTP/2 support

官网:
https://echo.labstack.com/

github地址:
https://github.com/labstack/echo

Star: 8707

获取:
go get github.com/labstack/echo

mysql

golang中使用MySQL请参考博客:
Go实战–go语言操作MySQL数据库(go-sql-driver/mysql)

这里就不详细介绍了。

实战

我们先建立一个MySQL的表,然后插入一些数据。

create table excuses (id char(20), quote char(20));1
insert into excuses (id, quote) VALUES ("1", "hey jude");1

代码:

package mainimport (    "database/sql"    "fmt"    "net/http"    _ "github.com/go-sql-driver/mysql"    "github.com/labstack/echo"    "github.com/labstack/echo/middleware")type (    Excuse struct {        Error string `json:"error"`        Id    string `json:"id"`        Quote string `json:"quote"`    })func main() {    // Echo instance    e := echo.New()    // Middleware    e.Use(middleware.Logger())    e.Use(middleware.Recover())    e.Use(middleware.CORSWithConfig(middleware.CORSConfig{        AllowOrigins: []string{"*"},        AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},    }))    // Route => handler    e.GET("/", func(c echo.Context) error {        db, err := sql.Open("mysql", "root:wangshubo@/test?charset=utf8")        if err != nil {            fmt.Println(err.Error())            response := Excuse{Id: "", Error: "true", Quote: ""}            return c.JSON(http.StatusInternalServerError, response)        }        defer db.Close()        var quote string        var id string        err = db.QueryRow("SELECT id, quote FROM excuses ORDER BY RAND() LIMIT 1").Scan(&id, "e)        if err != nil {            fmt.Println(err)        }        fmt.Println(quote)        response := Excuse{Id: id, Error: "false", Quote: quote}        return c.JSON(http.StatusOK, response)    })    e.GET("/id/:id", func(c echo.Context) error {        requested_id := c.Param("id")        fmt.Println(requested_id)        db, err := sql.Open("mysql", "root:wangshubo@/test?charset=utf8")        if err != nil {            fmt.Println(err.Error())            response := Excuse{Id: "", Error: "true", Quote: ""}            return c.JSON(http.StatusInternalServerError, response)        }        defer db.Close()        var quote string        var id string        err = db.QueryRow("SELECT id, quote FROM excuses WHERE id = ?", requested_id).Scan(&id, "e)        if err != nil {            fmt.Println(err)        }        response := Excuse{Id: id, Error: "false", Quote: quote}        return c.JSON(http.StatusOK, response)    })    e.Logger.Fatal(e.Start(":4000"))}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283

浏览器输入:
http://localhost:4000
http://localhost:4000/id/1

输出:

// 20171120170032// http://localhost:4000/id/1{  "error": "false",  "id": "1",  "quote": "hey jude"}12345678
622528a381e95bd28bf7cda5f6f61c21.gif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值