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

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, &quote)

        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, &quote)

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

这里写图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/wangshubo1989/article/details/78584145
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-25 16:35:40
  • 阅读 ( 2479 )
  • 分类:数据库

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢