使用Golang的echo库查询MariaDB的读取操作
我根据下一页内容进行了参考,谈论了使用Golang+Echo+dbr进行MySQL的CRUD操作和通过JSON返回数据库值的话题。
将从MariaDB读取的数据以JSON格式输出。
连接MySQL的信息
用户:scott
密码:tiger123
数据库:city
数据表名:cities
MariaDB的状态
$ mysql -uscott -ptiger123 city
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 24
Server version: 10.1.33-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [city]> select * from cities;
+-------+--------+------------+------------+
| id | name | population | date_mod |
+-------+--------+------------+------------+
| t3321 | 岡山 | 725139 | 2002-2-9 |
| t3322 | 倉敷 | 417328 | 2002-5-15 |
| t3323 | 津山 | 891654 | 2002-7-21 |
| t3324 | 玉野 | 265981 | 2002-11-12 |
| t3325 | 笠岡 | 284597 | 2002-4-24 |
| t3326 | 井原 | 671942 | 2002-2-8 |
| t3327 | 総社 | 265481 | 2002-8-3 |
| t3328 | 高梁 | 792356 | 2002-3-14 |
| t3329 | 新見 | 415892 | 2002-1-15 |
+-------+--------+------------+------------+
9 rows in set (0.00 sec)
MariaDB [city]>
// -----------------------------------------------------------------------
/*
server.go
Jun/11/2018
*/
// -----------------------------------------------------------------------
package main
import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
_ "github.com/go-sql-driver/mysql"
"github.com/gocraft/dbr"
)
type (
cityinfo struct {
ID string `db:"id"`
Name string `db:"name"`
Population int `db:"population"`
Date_mod string `db:"date_mod"`
}
responseData struct {
Users []cityinfo `json:"cities"`
}
)
var (
tablename = "cities"
seq = 1
conn, _ = dbr.Open("mysql", "scott:tiger123@tcp(127.0.0.1:3306)/city", nil)
sess = conn.NewSession(nil)
)
// -----------------------------------------------------------------------
func selectCities(c echo.Context) error {
var u []cityinfo
sess.Select("*").From(tablename).Load(&u)
response := new(responseData)
response.Users = u
return c.JSON(http.StatusOK,response)
}
// -----------------------------------------------------------------------
func main() {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Routes
e.GET("/cities/",selectCities)
// Start server
e.Start(":1323")
}
// -----------------------------------------------------------------------
服务器启动
go run server.go
客户端访问
curl http://localhost:1323/cities/ | jq .