原理
使用 Gin 框架 通过 http get 请求触发某包 某方法的执行操作, 从而返回数据
适合在程序运行不退出的情况下进行交互调试
配合 go-spew 使用效果更佳 https://github.com/davecgh/go-spew
Go 工程目录结构
.|-- go.mod|-- go.sum|-- main.go`-- testPackage`-- testPackage.go1 directory, 4 files
第五行为要调试的包
Go 文件 testPackage.go
package testPackageimport ("fmt")// 调试专用mapvar bug = make(map[string]interface{})// Http 请求调试入口func Debug() (i interface{}) {// 使用 http 访问进行某个包中某个方法的触发bug["person1"] = Person1{Name: "罗文猛",Age: 23,Sex: true,}bug["person2"] = GetTest()bug["person3"] = "罗文猛 23 true"fmt.Println(bug)return bug}// 包中的某个函数func GetTest() (ret2 interface{}) {// 匿名函数type Person2 struct {Name string `json:"name"`Age intsex bool // 男=true}person2 := Person2{Name: "罗文猛",Age: 23,sex: true,}return person2}type Person1 struct {Name stringAge int `json:"age"`Sex bool}
注意 29 行的匿名 结构体 Person2 将属性 sex 设置成了小写, 等下在 Http 触发调试中将不会显示
文件 main.go
package mainimport ("gin-debug/testPackage""github.com/gin-gonic/gin")func main() {r := gin.Default()// 使用 http 访问进行某个包中某个方法的触发r.GET("/debug/testPackage", func(c *gin.Context) {c.Header("Content-Type", "application/json")c.JSON(200, testPackage.Debug())})r.Run(":8080")}
使用HTTP 请求触发调试
// 20211226004502// http://192.168.66.104:8080/debug/testPackage{"person1": {"Name": "罗文猛","age": 23,"Sex": true},"person2": {"name": "罗文猛","Age": 23},"person3": "罗文猛 23 true"}
可以注意到 第10 行的对象 person2 没有了性别 sex
就是是说被调试的数据必须遵循导出原则
推荐浏览器上安装插件 JSON Viewer
可以展开折叠 JSON 数据, 方便调试
Chrome 商店下载 https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh
