基于go语言实现RestFul交互
一、RestFul
1.1 RestFul的介绍
RESTFUL(Representational State Transfer)是一种网络应用程序的设计风格和开发方式,基于HTTP或HTTPS,可以使用XML格式定义或JSON格式定义。RESTFUL适用于移动互联网厂商作为业务接口的场景,实现第三方OTT调用移动网络资源的功能,动作类型为新增、变更、删除所调用资源。
REST都倾向于用更加简单轻量的方法设计和实现。值得注意的是REST并没有一个明确的标准,而更像是一种设计的风格。
1.2 原则条件
-
REST 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是 RESTful
-
Web 应用程序最重要的 REST 原则是,客户端和服务器之间的交互在请求之间是无状态的,即:
1)从客户端到服务器的每个请求都必须包含理解请求所必须的信息
2)服务器在任何时间点重启,客户端都不会得到通知
3)无状态请求可以由任何可用服务器回答 -
在服务端,应用程序状态和功能可以分为各种资源
1.3 特点
- 每一个URI代表一种资源
- 客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源;
- 客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都必须包含理解请求所必需的信息
二、go中的gin包
Gin 是 Go语言写的一个 web 框架,它具有运行速度快,分组的路由器,良好的崩溃捕获和错误处理,非常好的支持中间件和 json。总之在 Go语言开发领域是一款值得好好研究的 Web 框架,开源网址:https://github.com/gin-gonic/gin
2.1 下载并加载gin包:
go get "https://github.com/gin-gonic/gin"
import "https://github.com/gin-gonic/gin"
2.2 gin包基于HTTP的简单使用
package main
import("fmt""https://github.com/gin-gonic/gin"
)
func main(){router := gin.Default()router.GET("/getConfig",func (context *gin.Context){context.JSON(http.StatusOK, gin.H{"code": http.StatusOK,"data": "message" })})router.Run(":8080")
}
2.3 gin包基于HTTPS的简单使用
package main
import("fmt""https://github.com/gin-gonic/gin"
)
func LoadTls(port int) gin.HandlerFunc {return func(c *gin.Context) {middleware := secure.New(secure.Options{SSLRedirect: true,SSLHost: "localhost:" + strconv.Itoa(port),})err := middleware.Process(c.Writer, c.Request)if err != nil {//如果出现错误,请不要继续。fmt.Println(err)return}// 继续往下处理c.Next()}
}
func main(){router := gin.Default()router.Use(LoadTls(8000))router.GET("/getConfig",func (context *gin.Context){context.JSON(http.StatusOK, gin.H{"code": http.StatusOK,"data": "message" })})router.RunTLS(":8080", "server.crt","server.key")
}
三、解析config.json文件服务器
3.1 设置接口和协议
type ConfigParseServer struct {
}func LoadTls(port int) gin.HandlerFunc {return func(c *gin.Context) {middleware := secure.New(secure.Options{SSLRedirect: true,SSLHost: "localhost:" + strconv.Itoa(port),})err := middleware.Process(c.Writer, c.Request)if err != nil {//如果出现错误,请不要继续。fmt.Println(err)return}// 继续往下处理c.Next()}
}func (*ConfigParseServer) GinHttps(isHttps bool) error {router := gin.Default()router.GET("/getConfigs/config", hello.GetAllConfigData)router.GET("/getConfig/server", hello.GetServerInfo)router.GET("/getConfig/client", hello.GetClientInfo)router.POST("/setServerInfo/", hello.SetServerInfo)router.POST("/setClientInfo/", hello.SetClientInfo)if isHttps {router.Use(LoadTls(8000))return router.RunTLS(":8000", "server.crt", "server.key")}return router.Run(":8080")
}func main() {var configParseServer ConfigParseServerfmt.Printf("请输入0/1来确定是否使用https: ")var valve boolfmt.Scan(&valve)configParseServer.GinHttps(valve)
}
3.2 实现接口
func GetJsonData() []byte {data, err := os.ReadFile("./hello/config.json")if err != nil {fmt.Println("readfile error")}return data
}func ParseJson2Struct() *AutoGenerated {datafig, err := os.ReadFile("./hello/config.json")if err != nil {fmt.Println("ParseJson: os.ReadFile.....")}cfg := new(AutoGenerated)err = json.Unmarshal(datafig, cfg)if err != nil {fmt.Println("ParseJson: json.Unmarshal.....")}return cfg
}func SetConfigInfo(context *gin.Context, modle string) (int, string) {var code int = -1var errorMessage stringraw := GetJsonData()var configStruct AutoGeneratederr := json.Unmarshal(raw, &configStruct)if err != nil {fmt.Println("SetConfigInfo: json.Unmarshal failed")}data, _ := io.ReadAll(context.Request.Body)var res map[string]interface{}err = json.Unmarshal(data, &res)if err != nil {fmt.Println("GetConfigInfo: json.Unmarshal failed...")}for k := range res {if k != modle {errorMessage = "Only the config of " + modle + " can be modified here"return code, errorMessage}}err = json.Unmarshal(data, &configStruct)if err != nil {Logger("Error", "json Unmarshal failed")errorMessage = "type of value is wrong"return code, errorMessage}Indata, err := json.MarshalIndent(configStruct, "", " ")if err != nil {fmt.Println("json.MarshalIndent failed")}fp, err := os.Create("./newConfig.json")if err != nil {fmt.Println("os.Create fail...")}defer fp.Close()fp.Write(Indata)code = 0errorMessage = "modify success!!!"return code, errorMessage
}
func SetServerInfo(context *gin.Context) {code, reason := SetConfigInfo(context, "server")var newConfig AutoGenerateddata, err := os.ReadFile("./newConfig.json")if err != nil {Logger("Error", "SetServerVersionInfo: ReadFile failed")}err = json.Unmarshal(data, &newConfig)if err != nil {Logger("Error", "SetServerVersionInfo: json Unmarshal failed")}var param interface{}if reason == "modify success!!!" {param = newConfig.Server} else {param = nil}context.JSON(http.StatusOK, gin.H{"code": code,"reason": reason,"params": param,})
}func SetClientInfo(context *gin.Context) {code, reason := SetConfigInfo(context, "client")var newConfig AutoGenerateddata, err := os.ReadFile("./newConfig.json")if err != nil {Logger("Error", "SetServerVersionInfo: ReadFile failed")}err = json.Unmarshal(data, &newConfig)if err != nil {Logger("Error", "SetServerVersionInfo: json Unmarshal failed")}var param interface{}if reason == "modify success!!!" {param = newConfig.Client} else {param = nil}context.JSON(http.StatusOK, gin.H{"code": code,"reason": reason,"params": param,})
}func GetConfigStruct() *AutoGenerated {//fmt.Println(*ParseJson2Struct())return ParseJson2Struct()
}func GetServerInfo(context *gin.Context) {context.JSON(http.StatusOK, gin.H{"code": http.StatusOK,//"reason": "get data success","data": GetConfigStruct().Server,})
}func GetClientInfo(context *gin.Context) {context.JSON(http.StatusOK, gin.H{"code": http.StatusOK,//"reason": "get data success","data": GetConfigStruct().Client,})
}
这个服务器部署完毕,在写代码中嵌套json信息取key是一个头疼的问题,写出如下代码
3.3 json取key
func getKeys(data map[string]interface{}) string {var j intvar flag intvar keyList []string//fmt.Println(len(data))for j = 0; j < 20; j++ {flag = 0for k, v := range data {keyList = append(keyList, k)switch value := v.(type) {case string, int, float64, uint:flag = -1case map[string]interface{}:data = valuefmt.Println(data)}}if flag == -1 {break}}queryString := keyList[0]var i intif len(keyList) > 1 {queryString += "."for i = 1; i < len(keyList)-1; i++ {queryString += keyList[i]queryString += "."}queryString += keyList[i]}return queryString //key的格式为key1.key2.key3...
}
//如上取到的key的格式,可以通过jmespath.Search去json中取相应的value
func getOneClassInfo(context *gin.Context, postJsondata []byte) {jsonData := GetJsonData()var totalData interface{}err := json.Unmarshal(jsonData, &totalData)if err != nil {fmt.Println("getServerInfo:111json.Unmarshal")}var jsonMap map[string]interface{}err = json.Unmarshal(postJsondata, &jsonMap)if err != nil {fmt.Println("getServerInfo:222json.Unmarshal")}path := getKeys(jsonMap)res, err := jmespath.Search(path, totalData)if err != nil {fmt.Println("jmespath Search failed....")}context.JSON(http.StatusOK, res)
}