加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:42:56 所属栏目:大数据 来源:网络整理
导读:生命不止,继续 go go go!!! 前面有几篇博客跟大家分享了一个golang的框架iris: Go实战–也许最快的Go语言Web框架kataras/iris初识四(i18n、filelogger、recaptcha) Go实战–也许最快的Go语言Web框架kataras/iris初识三(Redis、leveldb、BoltDB) Go实战–也

生命不止,继续 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,quote FROM excuses WHERE id = ?",requested_id).Scan(&id,&quote)

        if err != nil {
            fmt.Println(err)
        }

        response := Excuse{Id: id,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"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读