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

前端之家收集整理的这篇文章主要介绍了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,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"
}
原文链接:/go/187662.html

猜你在找的Go相关文章