Go实战--golang中使用echo和MySQL搭建api(labstack/echo、go-sql-driver/mysql)

生命不止,继续 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));
insert into excuses (id, quote) VALUES ("1", "hey jude");

代码:

package main

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

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

输出:

// 20171120170032
// http://localhost:4000/id/1

{
  "error": "false",
  "id": "1",
  "quote": "hey jude"
}

Go实战--golang中使用echo和MySQL搭建api(labstack/echo、go-sql-driver/mysql)_第1张图片

你可能感兴趣的:(go,Go从不放弃到实战)