Created
March 2, 2017 11:49
-
-
Save YCF/e8519c39f9dd83e383f7c38a16f38890 to your computer and use it in GitHub Desktop.
查询数据库输出为json的例子
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"strings" | |
"github.com/go-ini/ini" | |
"github.com/labstack/echo" | |
_ "github.com/mattn/go-sqlite3" | |
) | |
func GetOption(section string, key string) (conf string) { | |
cfg, err := ini.InsensitiveLoad("./conf.ini") | |
conf = cfg.Section(section).Key(key).String() | |
if err != nil { | |
fmt.Println(err) | |
} | |
return conf | |
} | |
func main() { | |
e := echo.New() | |
e.GET("/sqlite/:query", func(c echo.Context) error { | |
dbSource := GetOption("Database", "Sqlite") | |
db, _ := sql.Open("sqlite3", dbSource) | |
if c.Param("query") == "" { | |
return c.String(http.StatusOK, "no query") | |
} | |
q := c.Param("query") | |
qStr := GetOption("Query", q) | |
if qStr == "" { | |
return c.String(http.StatusOK, "no query") | |
} | |
stmt, err := db.Prepare(qStr) | |
if err != nil { | |
return err | |
} | |
defer stmt.Close() | |
rows, err := stmt.Query() | |
if err != nil { | |
return err | |
} | |
defer rows.Close() | |
columns, err := rows.Columns() | |
if err != nil { | |
return err | |
} | |
count := len(columns) | |
tableData := make([]map[string]interface{}, 0) | |
values := make([]interface{}, count) | |
valuePtrs := make([]interface{}, count) | |
for rows.Next() { | |
for i := 0; i < count; i++ { | |
valuePtrs[i] = &values[i] | |
} | |
rows.Scan(valuePtrs...) | |
entry := make(map[string]interface{}) | |
for i, col := range columns { | |
var v interface{} | |
val := values[i] | |
b, ok := val.([]byte) | |
if ok { | |
v = string(b) | |
} else { | |
v = val | |
} | |
entry[col] = v | |
} | |
tableData = append(tableData, entry) | |
} | |
jsonData, err := json.Marshal(tableData) | |
if err != nil { | |
return err | |
} | |
return c.String(http.StatusOK, string(jsonData)) | |
}) | |
e.Logger.Fatal(e.Start(":1323")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment