ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

【REST2SQL】03 GO读取JSON文件

2026/9/9 4:43:33 拓冰建站 浏览量
【REST2SQL】03 GO读取JSON文件

REST2SQL需要一些配置信息,用JSON文件保存,比如config.json

在这里插入图片描述

1 创建config.json配置文件

{"hostPort":"localhost:5217","connString":"oracle://blma:5217@127.0.0.1:1521/CQYH","_oracle":"oracle://blma:5217@127.0.0.1:1521/CQYH","_mysql":"mysql://","_mssql":"mssql://","_postgresql":"postgresql://","REST":"GET,POST,PUT,DELETE", "_REST":"GET,POST,PUT,DELETE", "SQL":"SELECT","_SQL":"SELECT,INSERT,UPDATE,DELETE"}

其中_下划线开头的作为注释项。

2 创建一个Gojson的控制台程序

2.1 引入json和ioutil包

import ("encoding/json""fmt""io/ioutil"
)

2.2 创建配置项结构体

// 配置结构体
type Config struct {DBType     string //数据库类型 :oracle、mysql等ConnString string `json:"connString"`HostPort   string `json:"hostPort"`REST       string `json:"REST"`SQL        string `json:"SQL"`
}

反引号包裹的为json文件的键。
5个键分别为数据库类型,数据库连接字符串,http主机和端口,REST可用方法,SQL可用语句。

2.3 主控main()函数

func main() {fmt.Println("Go Read JSON")bytes, err := ioutil.ReadFile("config.json")if err != nil {fmt.Println("读取json文件失败", err)return}conf := &Config{}err = json.Unmarshal(bytes, conf)if err != nil {fmt.Println("json解析失败", err)return}fmt.Println(conf)fmt.Println("DBType:", conf.DBType)fmt.Println("connString:", conf.ConnString)fmt.Println("hostPort:", conf.HostPort)fmt.Println("REST:", conf.REST)fmt.Println("SQL:", conf.SQL)
}

3 go读取json全部代码

// gojson project main.go
// go 读取 Json 文件测试
package mainimport ("encoding/json""fmt""io/ioutil"
)// 配置结构体
type Config struct {DBType     string //数据库类型 :oracle、mysql等ConnString string `json:"connString"`HostPort   string `json:"hostPort"`REST       string `json:"REST"`SQL        string `json:"SQL"`
}func main() {fmt.Println("Go Read JSON")bytes, err := ioutil.ReadFile("config.json")if err != nil {fmt.Println("读取json文件失败", err)return}conf := &Config{}err = json.Unmarshal(bytes, conf)if err != nil {fmt.Println("json解析失败", err)return}fmt.Println(conf)fmt.Println("DBType:", conf.DBType)fmt.Println("connString:", conf.ConnString)fmt.Println("hostPort:", conf.HostPort)fmt.Println("REST:", conf.REST)fmt.Println("SQL:", conf.SQL)
}

4 执行结果

Go Read JSON
&{ oracle://blma:5217@127.0.0.1:1521/CQYH localhost:5217 GET,POST,PUT,DELETE SELECT}
DBType:
connString: oracle://blma:5217@127.0.0.1:1521/CQYH
hostPort: localhost:5217
REST: GET,POST,PUT,DELETE
SQL: SELECT