当前位置: 首页 > news >正文

go编解码json和http请求

1.json概述

json是日常工作中http请求的最重要的数据格式。对比日常使用python中的json,获得http请求后json.loads和json.dumps函数,go中显的非常麻烦,这里结合json和http请求的总结下,便于积累和学习。这里给出一个json的类型,包括了数组对象等各种格式,以请求云计算的伸缩组的接口为例

{"ResponseMetadata": {"RequestId": "202504291928461ASBCDEDGSGGSBCD8A4862","Action": "DescribeScalingGroups","Version": "2020-01-01","Service": "auto_scaling","Region": "cn-beijing"},"Result": {"ScalingGroups": [{"ScalingGroupId": "scg-ydukizremqd0qsyqoc0k","ScalingGroupName": "test_create_recurrence_policy_without_end_time","LifecycleState": "Active","HealthCheckType": "ECS","VpcId": "vpc-2ff4fh7wic2dc59gp67u70mpn","SubnetIds": ["subnet-imc2pmpasbuo8gbssz4tv3cw"],"DefaultCooldown": 5,"ActiveScalingConfigurationId": "scc-ydukizstwjiq4jg1ggfy","DesireInstanceNumber": 2,"MinInstanceNumber": 0,"MaxInstanceNumber": 10,"InstanceTerminatePolicy": "OldestScalingConfigurationWithNewestInstance","ServerGroupAttributes": [],"CreatedAt": "2025-04-27T07:53:37Z","UpdatedAt": "2025-04-27T16:00:00Z","TotalInstanceCount": 2,"DBInstanceIds": [],"MultiAZPolicy": "BALANCE","LaunchTemplateId": "","LaunchTemplateVersion": "","DesireCapacityType": "units","MinSize": 0,"MaxSize": 0,"DesireCapacity": -1,"TotalCapacity": 0,"LaunchTemplateOverrides": [],"ScalingMode": "release","StoppedInstanceCount": 0,"StoppedCapacity": 0,"ProjectName": "default","Tags": [{"Key": "k1","Value": "v1"}],"LoadBalancerHealthCheckGracePeriod": 300,"InstancesDistribution": {"OnDemandBaseCapacity": 0,"OnDemandPercentageAboveBaseCapacity": 0,"CompensateWithOnDemand": false,"SpotInstanceRemedy": false},"SuspendedProcesses": []}],"NextToken": ""}
}

这个是调用DescribeScalingGroups接口查询指定ScalingGroupId参数的响应结果。这里先声明两个概念

序列化和反序列化

  • 序列化

就是将对象转化成二进制序列的过程。我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。

  • 反序列化

就是讲二进制序列转化成对象的过程。 把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。

实际工作中,解析返回到JSON有三种方式:

  • 解析到结构体,使用map[string]interfance{}先接过来
  • 解析到interface,使用map[string]interface{}先接过来
  • 第三方包SimpleJSON,单纯的数据解析

上述的JSON返回数据,因为查询了指定的ScalingGroupId,希望在ScalingGroups结果判断下伸缩组的状态LifecycleState是否是Active。

查询接口DescribeScalingGroups返回的结果*output如下所示

map[ResponseMetadata:map[Action:DescribeScalingGroups Region:cn-beijing RequestId:20250429200529F297B9ADFGHJKDS96346 Service:auto_scaling Version:2020-01-01] Result:map[PageNumber:1 PageSize:10 ScalingGroups:[map[ActiveScalingConfigurationId:scc-ydukizstwjiq4jg1ggfy CreatedAt:2025-04-27T07:53:37Z DBInstanceIds:[] DefaultCooldown:5 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:2 HealthCheckType:ECS InstanceTerminatePolicy:OldestScalingConfigurationWithNewestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId: LaunchTemplateOverrides:[] LaunchTemplateVersion: LifecycleState:Active LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:10 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:BALANCE ProjectName:default ScalingGroupId:scg-ydukizremqd0qsyqoc0k ScalingGroupName:test_create_recurrence_policy_without_end_time ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-imc2pmpasbuo8gbssz4tv3cw] SuspendedProcesses:[] Tags:[map[Key:k1 Value:v1]] TotalCapacity:0 TotalInstanceCount:2 UpdatedAt:2025-04-27T16:00:00Z VpcId:vpc-2ff4fh7wic2dc59gp67u70mpn] map[ActiveScalingConfigurationId:scc-ydufdt2e8dd0qtlr2121 CreatedAt:2025-04-25T08:25:00Z DBInstanceIds:[] DefaultCooldown:300 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:-1 HealthCheckType:ECS InstanceTerminatePolicy:OldestScalingConfigurationWithOldestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId: LaunchTemplateOverrides:[] LaunchTemplateVersion: LifecycleState:Active LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:1 MaxSize:0 MinInstanceNumber:1 MinSize:0 MultiAZPolicy:PRIORITY ProjectName:default ScalingGroupId:scg-ydufdqucghiq4k6pncgf ScalingGroupName:tjhs ScalingMode:recycle ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-imdl1ew9i03k8gbssyvxv53q] SuspendedProcesses:[] Tags:[] TotalCapacity:0 TotalInstanceCount:1 UpdatedAt:2025-04-25T08:25:59Z VpcId:vpc-imbcb3doyr5s8gbssxzkz7zt] map[ActiveScalingConfigurationId: CreatedAt:2025-04-25T08:10:17Z DBInstanceIds:[] DefaultCooldown:300 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:1 HealthCheckType:ECS InstanceTerminatePolicy:NewestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId: LaunchTemplateOverrides:[] LaunchTemplateVersion: LifecycleState:InActive LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:100 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:PRIORITY ProjectName:default ScalingGroupId:scg-ydufcse0jaiq4k3hz5nw ScalingGroupName:wxy-recycle-混合计费缩容4 ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-12arsfcvsqvi817q7y2rplfif] SuspendedProcesses:[] Tags:[map[Key:volc:vke:Id Value:1]] TotalCapacity:0 TotalInstanceCount:0 UpdatedAt:2025-04-25T08:10:17Z VpcId:vpc-imbcb3doyr5s8gbssxzkz7zt] map[ActiveScalingConfigurationId: CreatedAt:2025-04-25T06:08:23Z DBInstanceIds:[] DefaultCooldown:300 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:1 HealthCheckType:ECS InstanceTerminatePolicy:NewestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId: LaunchTemplateOverrides:[] LaunchTemplateVersion: LifecycleState:InActive LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:100 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:PRIORITY ProjectName:default ScalingGroupId:scg-yduf4uysvnd0qs4juwot ScalingGroupName:wxy-recycle-混合计费缩容2 ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-12arsfcvsqvi817q7y2rplfif] SuspendedProcesses:[] Tags:[] TotalCapacity:0 TotalInstanceCount:0 UpdatedAt:2025-04-25T06:08:23Z VpcId:vpc-imbcb3doyr5s8gbssxzkz7zt] map[ActiveScalingConfigurationId:scc-yduc64xga6d0qsvqjf7d CreatedAt:2025-04-24T02:46:41Z DBInstanceIds:[] DefaultCooldown:5 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:12 HealthCheckType:ECS InstanceTerminatePolicy:OldestScalingConfigurationWithOldestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId: LaunchTemplateOverrides:[] LaunchTemplateVersion: LifecycleState:Active LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:100 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:PRIORITY ProjectName:default ScalingGroupId:scg-yduc63lnuqiq4k6il4vh ScalingGroupName:wxy-metric-test ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-imdl1ew9i03k8gbssyvxv53q] SuspendedProcesses:[] Tags:[map[Key:sys Value:]] TotalCapacity:0 TotalInstanceCount:11 UpdatedAt:2025-04-28T16:00:00Z VpcId:vpc-imbcb3doyr5s8gbssxzkz7zt] map[ActiveScalingConfigurationId:scc-ydu5dwgxt1d6kr6rf3j7 CreatedAt:2025-04-21T12:11:32Z DBInstanceIds:[] DefaultCooldown:5 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:0 HealthCheckType:ECS InstanceTerminatePolicy:OldestScalingConfigurationWithNewestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId: LaunchTemplateOverrides:[] LaunchTemplateVersion: LifecycleState:Active LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:900 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:BALANCE ProjectName:default ScalingGroupId:scg-ydu5dwe4nnd6kqpbsbuc ScalingGroupName:test_e9aef648-ed16-4807-b294-3118cbb94430 ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-2fe72h3r8pr7k59gp68yogx1p subnet-12bhi1j0k4buo17q7y2aet40a] SuspendedProcesses:[] Tags:[] TotalCapacity:0 TotalInstanceCount:0 UpdatedAt:2025-04-25T07:34:48Z VpcId:vpc-2ff4fh7wic2dc59gp67u70mpn] map[ActiveScalingConfigurationId:scc-ydu5cvr4go7h70rs17oq CreatedAt:2025-04-21T11:55:51Z DBInstanceIds:[] DefaultCooldown:5 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:0 HealthCheckType:ECS InstanceTerminatePolicy:OldestScalingConfigurationWithNewestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId: LaunchTemplateOverrides:[] LaunchTemplateVersion: LifecycleState:Active LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:900 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:PRIORITY ProjectName:default ScalingGroupId:scg-ydu5cvobb67h7110nsqr ScalingGroupName:test_make_effort_to_provision_esi_instance_auto_scaling0 ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-2fe72h3r8pr7k59gp68yogx1p subnet-in29bofzzfuo8gbssxhpj6pr] SuspendedProcesses:[] Tags:[] TotalCapacity:0 TotalInstanceCount:0 UpdatedAt:2025-04-27T07:50:29Z VpcId:vpc-2ff4fh7wic2dc59gp67u70mpn] map[ActiveScalingConfigurationId: CreatedAt:2025-04-21T09:12:38Z DBInstanceIds:[] DefaultCooldown:300 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:0 HealthCheckType:ECS InstanceTerminatePolicy:OldestScalingConfigurationWithOldestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId:lt-ydu521mjhd4pf5w7iffd LaunchTemplateOverrides:[] LaunchTemplateVersion:Default LifecycleState:InActive LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:900 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:PRIORITY ProjectName:default ScalingGroupId:scg-ydu529hknc7h711wnzt7 ScalingGroupName:任华西-esi-segmented ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-in29bofzzfuo8gbssxhpj6pr] SuspendedProcesses:[] Tags:[] TotalCapacity:0 TotalInstanceCount:0 UpdatedAt:2025-04-21T09:12:38Z VpcId:vpc-2ff4fh7wic2dc59gp67u70mpn] map[ActiveScalingConfigurationId: CreatedAt:2025-04-21T09:03:03Z DBInstanceIds:[] DefaultCooldown:5 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:0 HealthCheckType:ECS InstanceTerminatePolicy:OldestScalingConfigurationWithOldestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId:lt-ydt96663gx4pf62xh0w1 LaunchTemplateOverrides:[] LaunchTemplateVersion:Default LifecycleState:Active LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:900 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:BALANCE ProjectName:default ScalingGroupId:scg-ydu51n3ag57h71541h5j ScalingGroupName:test_make_effort_to_provision_esi_instance_with_modify_policy_auto_scaling0 ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-in29bofzzfuo8gbssxhpj6pr] SuspendedProcesses:[] Tags:[] TotalCapacity:0 TotalInstanceCount:0 UpdatedAt:2025-04-22T07:14:04Z VpcId:vpc-2ff4fh7wic2dc59gp67u70mpn] map[ActiveScalingConfigurationId:scc-ydtx5nu76w7h70wslv7c CreatedAt:2025-04-18T08:16:10Z DBInstanceIds:[] DefaultCooldown:5 DesireCapacity:-1 DesireCapacityType:units DesireInstanceNumber:0 HealthCheckType:ECS InstanceTerminatePolicy:NewestInstance InstancesDistribution:map[CompensateWithOnDemand:false OnDemandBaseCapacity:0 OnDemandPercentageAboveBaseCapacity:0 SpotInstanceRemedy:false] LaunchTemplateId: LaunchTemplateOverrides:[] LaunchTemplateVersion: LifecycleState:Active LoadBalancerHealthCheckGracePeriod:300 MaxInstanceNumber:10 MaxSize:0 MinInstanceNumber:0 MinSize:0 MultiAZPolicy:BALANCE ProjectName:default ScalingGroupId:scg-ydtx5nssrpd6ksegkwyp ScalingGroupName:test_create_alarm_policy_and_specify_effective_time_auto_scaling0 ScalingMode:release ServerGroupAttributes:[] StoppedCapacity:0 StoppedInstanceCount:0 SubnetIds:[subnet-imc2pmpasbuo8gbssz4tv3cw] SuspendedProcesses:[] Tags:[] TotalCapacity:0 TotalInstanceCount:0 UpdatedAt:2025-04-21T06:05:49Z VpcId:vpc-2ff4fh7wic2dc59gp67u70mpn]] TotalCount:19]]

如果通过如下“美化”,可以输出到按照最初给出实例一样展示出来

	jsonData, _ := json.MarshalIndent(output, "", "  ")fmt.Println(string(jsonData))

json.MarshalIndent(output, "", " ")

  • 将 Go 的结构体(或任意可序列化的值)output 转换成 格式化后的 JSON 字符串

  • 第二个参数是前缀(通常设为 ""),第三个参数是每层缩进的字符串(这里是两个空格 " ")。

  • 返回的是一个 []byte 类型的 JSON 数据。

  • 将[]byte类型的JSON数据转换成go中的string类型,方便控制台输出用于调试。

json.MarshalIndent(...) + Println打印结构,用于调试

2.完全解析到结构体

参考上面的JSON响应,我们需要定义与之对应的结构体

// ResponseMetadata 定义响应元数据部分
type ResponseMetadata struct {Action    string `json:"Action"`Region    string `json:"Region"`RequestId string `json:"RequestId"`Service   string `json:"Service"`Version   string `json:"Version"`
}// InstancesDistribution 定义实例分布信息
type InstancesDistribution struct {CompensateWithOnDemand              bool `json:"CompensateWithOnDemand"`OnDemandBaseCapacity                int  `json:"OnDemandBaseCapacity"`OnDemandPercentageAboveBaseCapacity int  `json:"OnDemandPercentageAboveBaseCapacity"`SpotInstanceRemedy                  bool `json:"SpotInstanceRemedy"`
}// Tag 定义标签信息
type Tag struct {Key   string `json:"Key"`Value string `json:"Value"`
}// ScalingGroup 定义伸缩组信息
type ScalingGroup struct {ActiveScalingConfigurationId       string                `json:"ActiveScalingConfigurationId"`CreatedAt                          string                `json:"CreatedAt"`DBInstanceIds                      []string              `json:"DBInstanceIds"`DefaultCooldown                    int                   `json:"DefaultCooldown"`DesireCapacity                     int                   `json:"DesireCapacity"`DesireCapacityType                 string                `json:"DesireCapacityType"`DesireInstanceNumber               int                   `json:"DesireInstanceNumber"`HealthCheckType                    string                `json:"HealthCheckType"`InstanceTerminatePolicy            string                `json:"InstanceTerminatePolicy"`InstancesDistribution              InstancesDistribution `json:"InstancesDistribution"`LaunchTemplateId                   string                `json:"LaunchTemplateId"`LaunchTemplateOverrides            []interface{}         `json:"LaunchTemplateOverrides"`LaunchTemplateVersion              string                `json:"LaunchTemplateVersion"`LifecycleState                     string                `json:"LifecycleState"`LoadBalancerHealthCheckGracePeriod int                   `json:"LoadBalancerHealthCheckGracePeriod"`MaxInstanceNumber                  int                   `json:"MaxInstanceNumber"`MaxSize                            int                   `json:"MaxSize"`MinInstanceNumber                  int                   `json:"MinInstanceNumber"`MinSize                            int                   `json:"MinSize"`MultiAZPolicy                      string                `json:"MultiAZPolicy"`ProjectName                        string                `json:"ProjectName"`ScalingGroupId                     string                `json:"ScalingGroupId"`ScalingGroupName                   string                `json:"ScalingGroupName"`ScalingMode                        string                `json:"ScalingMode"`ServerGroupAttributes              []interface{}         `json:"ServerGroupAttributes"`StoppedCapacity                    int                   `json:"StoppedCapacity"`StoppedInstanceCount               int                   `json:"StoppedInstanceCount"`SubnetIds                          []string              `json:"SubnetIds"`SuspendedProcesses                 []interface{}         `json:"SuspendedProcesses"`Tags                               []Tag                 `json:"Tags"`TotalCapacity                      int                   `json:"TotalCapacity"`TotalInstanceCount                 int                   `json:"TotalInstanceCount"`UpdatedAt                          string                `json:"UpdatedAt"`VpcId                              string                `json:"VpcId"`
}// Result 定义结果部分
type Result struct {PageNumber    int            `json:"PageNumber"`PageSize      int            `json:"PageSize"`ScalingGroups []ScalingGroup `json:"ScalingGroups"`
}// Response 定义整个响应结构
type Response struct {ResponseMetadata ResponseMetadata `json:"ResponseMetadata"`Result           Result           `json:"Result"`
}

使用上面的结构体查询并遍历最终的结果

func DescribeScalingGroups(session *session.Session) {// 构建自定义GET请求universalReq := universal.RequestUniversal{ServiceName: "auto_scaling",Action:      "DescribeScalingGroups",Version:     "2020-01-01",HttpMethod:  universal.GET,}// 创建自定义GET客户端universal := universal.New(session)// 目标 ScalingGroupIdtargetId := "scg-ydu51n3ag57h71541h5j"// 指定参数形式parameters := map[string]interface{}{"ScalingGroupIds.1": targetId,}output, err := universal.DoCall(universalReq, &parameters)if err != nil {panic(err)}fmt.Println(*output)// 假设 output 是从 DoCall 返回的 *Response 类型// jsonData, _ := json.MarshalIndent(output, "", "  ")// fmt.Println(string(jsonData))// 将 output 映射到 Response 结构体var resp Responsedata, err := json.Marshal(output) // 将output 转换为 JSON 格式的字节流([]byte)if err != nil {panic(err)}err = json.Unmarshal(data, &resp) // 使用 json.Unmarshal 函数将上述得到的 JSON 字节流反序列化到 resp 变量中if err != nil {fmt.Println("Error unmarshalling JSON:", err)return}// 查找并打印 LifecycleStatefor _, group := range resp.Result.ScalingGroups {if group.ScalingGroupId == targetId {fmt.Printf("ScalingGroupId %s has LifecycleState: %s\n", targetId, group.LifecycleState)return}}fmt.Printf("ScalingGroupId %s not found.\n", targetId)}

3.简化解析到结构体

我们发现我们只需要比如ScalingGroupId和LifecycleState,甚至是部分的Metadata元数据,其他的很多数据都不需要使用,“感觉”没有必要定义。这个感觉是对的,很多语言就是这样,编程语言是面向人的,给机器使用的。

// ResponseMetadata 定义响应元数据部分,如果不需要可以省略或简化
type ResponseMetaData struct {Action  string `json:"Action"`Region  string `json:"Region"`Request string `json:"Request"`
}// ScalingGroup,只定义需要的字段
type ScalingGroup struct {ScalingGroupId string `json:"ScalingGroupId"`LifecycleState string `json:"LifecycleState"`
}// 定义结果部分
type Result struct {ScalingGroups []ScalingGroup `json:"ScalingGroups"`
}// 定义整个响应结构
type Response struct {ResponseMetaData ResponseMetaData `json:"ResponseMetaData"`Result           Result           `json:"Result"`
}

封装查询接口

func DescribeScalingGroups(session *session.Session) {// 构建自定义GET请求universalReq := universal.RequestUniversal{ServiceName: "auto_scaling",Action:      "DescribeScalingGroups",Version:     "2020-01-01",HttpMethod:  universal.GET,}// 创建自定义GET客户端universal := universal.New(session)// 发起请求并处理返回或异常parameters := make(map[string]interface{})output, err := universal.DoCall(universalReq, &parameters)if err != nil {panic(err)}fmt.Println(*output)// 假设 output 是从 DoCall 返回的 *Response 类型// jsonData, _ := json.MarshalIndent(output, "", "  ")// fmt.Println(string(jsonData))// 将 output 映射到 Response 结构体var resp Responsedata, err := json.Marshal(output) // 将output 转换为 JSON 格式的字节流([]byte)if err != nil {panic(err)}err = json.Unmarshal(data, &resp) // 使用 json.Unmarshal 函数将上述得到的 JSON 字节流反序列化到 resp 变量中if err != nil {fmt.Println("Error unmarshalling JSON:", err)return}// 目标 ScalingGroupIdtargetId := "scg-ydu51n3ag57h71541h5j"// 查找并打印 LifecycleStatefor _, group := range resp.Result.ScalingGroups {if group.ScalingGroupId == targetId {fmt.Printf("ScalingGroupId %s has LifecycleState: %s\n", targetId, group.LifecycleState)return}}fmt.Printf("ScalingGroupId %s not found.\n", targetId)}

4.解析到interface

我们知道Interface{}可以用来存储任何类型的对象,这样数据结构正好可以存储解析繁琐嵌套的JSON结果,JSON包中采用的map[string]interface{}和[]interface{}结构来存储任意的JSON对象和数组。所以任何结构我们都可以定义并解析到Interface{}里面

response := []byte(`{"RequestId":"202504291928461ADFGHJKCD8A4862","Action":"DescribeScalingGroups","ScalingGroups":["scalingGroupId1","scalingGroupId2"]}`)var f interface{}
err := json.Unmarshal{response, &b}

这个时候f里面就存储了一个map类型,他们的key是string,值存储在空的interface{}中的

f = map[string]interface{}{"RequestId":"202504291928461ADFGHJKCD8A4862","Action":"DescribeScalingGroups","ScalingGroups":[]interface{}{"scalingGroupId1","scalingGroupId2",},
}

那如何来访问需要的LifecycleState字段呢,可以通过断言的方式

m := f.(map[string]interface{})

接着给出示例

func DescribeScalingGroups(session *session.Session) {// 构建自定义GET请求universalReq := universal.RequestUniversal{ServiceName: "auto_scaling",Action:      "DescribeScalingGroups",Version:     "2020-01-01",HttpMethod:  universal.GET,}// 创建自定义GET客户端universal := universal.New(session)// 发起请求并处理返回或异常parameters := make(map[string]interface{})output, err := universal.DoCall(universalReq, &parameters)if err != nil {panic(err)}fmt.Println(*output)// 假设 output 是从 DoCall 返回的 *Response 类型// jsonFormateData, _ := json.MarshalIndent(output, "", "  ")// fmt.Println(string(jsonFormateData))// 查找并打印 LifecycleStatejsonData, err := json.Marshal(output) // 将output 转换为 JSON 格式的字节流([]byte)if err != nil {panic(err)}var x interface{}err = json.Unmarshal(jsonData, &x)if err != nil {fmt.Println("Error unmarshalling JSON:", err)return}fmt.Println("x contains: ", x)fmt.Println("===============")// 类型断言为 map[string]interface{}m := x.(map[string]interface{})// 访问 Result 下的 ScalingGroupsresult := m["Result"].(map[string]interface{})scalingGroups := result["ScalingGroups"].([]interface{})// 目标 ScalingGroupIdtargetId := "scg-ydu51n3ag57h71541h5j"// 查找并打印 LifecycleStatefor _, item := range scalingGroups {group := item.(map[string]interface{})scalingGroupId := group["ScalingGroupId"].(string)lifecycleState := group["LifecycleState"].(string)if scalingGroupId == targetId {fmt.Printf("ScalingGroupId %s has LifecycleState: %s\n", targetId, lifecycleState)return}}fmt.Printf("ScalingGroupId %s not found.\n", targetId)}

4.使用第三方包SimpleJSON

既然要使用第三方的包,需要先安装

go get "github.com/bitly/go-simplejson"

这里直接给出示例

func DescribeScalingGroups(session *session.Session) {// 构建自定义GET请求universalReq := universal.RequestUniversal{ServiceName: "auto_scaling",Action:      "DescribeScalingGroups",Version:     "2020-01-01",HttpMethod:  universal.GET,}// 创建自定义GET客户端universal := universal.New(session)// 发起请求并处理返回或异常parameters := make(map[string]interface{})output, err := universal.DoCall(universalReq, &parameters)if err != nil {panic(err)}fmt.Println(*output)// 假设 output 是从 DoCall 返回的 *Response 类型// jsonData, _ := json.MarshalIndent(output, "", "  ")// fmt.Println(string(jsonData))// 查找并打印 LifecycleStatedata, err := json.Marshal(output) // 将output 转换为 JSON 格式的字节流([]byte)if err != nil {panic(err)}// Step 2: 用 simplejson 解析simpleJsonData, err := simplejson.NewJson(data)if err != nil {fmt.Println("Failed to parse JSON:", err)return}// Step 3: 查找目标 ScalingGroupIdtargetId := "scg-ydu51n3ag57h71541h5j"scalingGroups, err := simpleJsonData.Get("Result").Get("ScalingGroups").Array()if err != nil {fmt.Println("Error getting ScalingGroups array:", err)return}for _, item := range scalingGroups {group := item.(map[string]interface{})scalingGroupId := group["ScalingGroupId"].(string)lifecycleState := group["LifecycleState"].(string)if scalingGroupId == targetId {fmt.Printf("Found LifecycleState: %s\n", lifecycleState)return}}}

5.编解码

5.1 Marshal*

上文中看到了Marshal()和MarshalIndent()函数可以将数据封装成json数据。

  • struct、slice、array、map都可以转换成json
  • struct转换成json的时候,只有字段首字母大写的才会被转换
  • map转换的时候,key必须为string
  • 封装的时候,如果是指针,会追踪指针指向的对象进行封装

先有数据结构,然后Marshal。JSON包里Marshal函数来处理,函数定义如下:

func Marshal(v interface{}) ([]byte, error)
package mainimport ("encoding/json""fmt"
)type Server struct {ServerName stringServerIP   string
}type Serverslice struct {Servers []Server
}func main() {var s Serverslices.Servers = append(s.Servers, Server{ServerName: "ecs", ServerIP: "127.0.0.1"})s.Servers = append(s.Servers, Server{ServerName: "auto_scaling", ServerIP: "127.0.0.2"})b, err := json.Marshal(s)if err != nil {fmt.Println("json err:", err)}fmt.Println(string(b))
}

输出结果如下所示:

{"Servers":[{"ServerName":"ecs","ServerIP":"127.0.0.1"},{"ServerName":"auto_scaling","ServerIP":"127.0.0.2"}]}

5.2 json.NewEncoder和json.NewDecoder

除了marshal和unmarshal函数,Go还提供了Decoder和Encoder对streamJSON进行处理,常见 request中的Body、文件等。

// 编码
json.NewEncoder(<Writer>).encode(v)
json.Marshal(&v)// 解码
json.NewDecoder(<Reader>).decode(&v)
json.Unmarshal([]byte, &v)

5.3 Marshal vs jons.New*coder

package mainimport ("encoding/json""fmt""bytes""strings"
)type Person struct {Name string `json:"name"`Age int `json:"age"`
}func main()  {// 1. 使用 json.Marshal 编码person1 := Person{"zhangsan", 35}bytes1, err := json.Marshal(&person1)if err == nil {// 返回的是字节数组 []bytefmt.Println("json.Marshal 编码结果: ", string(bytes1))}// 2. 使用 json.Unmarshal 解码str := `{"name":"lisi","age":35}`// json.Unmarshal 需要字节数组参数, 需要把字符串转为 []byte 类型bytes2 := []byte(str) // 字符串转换为字节数组var person2 Person    // 用来接收解码后的结果if json.Unmarshal(bytes2, &person2) == nil {fmt.Println("json.Unmarshal 解码结果: ", person2.Name, person2.Age)}// 3. 使用 json.NewEncoder 编码person3 := Person{"wangwu", 35}// 编码结果暂存到 bufferbytes3 := new(bytes.Buffer)_ = json.NewEncoder(bytes3).Encode(person3)if err == nil {fmt.Print("json.NewEncoder 编码结果: ", string(bytes3.Bytes()))}// 4. 使用 json.NewDecoder 解码str4 := `{"name":"lier","age":34}`var person4 Person// 创建一个 string reader 作为参数err = json.NewDecoder(strings.NewReader(str4)).Decode(&person4)if err == nil {fmt.Println("json.NewDecoder 解码结果: ", person4.Name, person4.Age)}
}

相关文章:

go编解码json和http请求

1.json概述 json是日常工作中http请求的最重要的数据格式。对比日常使用python中的json&#xff0c;获得http请求后json.loads和json.dumps函数&#xff0c;go中显的非常麻烦&#xff0c;这里结合json和http请求的总结下&#xff0c;便于积累和学习。这里给出一个json的类型&a…...

洛谷题解 | CF1979C Earning on Bets

目录 题目描述输入格式输出格式输入输出样例 #1输入 #1输出 #1 说明/提示题目思路AC 代码 题目描述 You have been offered to play a game. In this game, there are $ n $ possible outcomes, and for each of them, you must bet a certain integer amount of coins. In th…...

在线文章系统自动化测试报告

目录 1. 项目简介 1.1. 用户登录页面 1.2. 文章列表页面 1.3. 文章详情页面 1.4. 文章编辑与发布页面 2. 测试计划 3. 测试环境/工具/技术栈 4. 编写自动化测试用例​编辑 5. 自动化测试脚本开发 5.1. 项目整体结构 5.2. 配置utils.py 5.2.1. 导入必要的库 5.2.2.…...

C++ 类和对象(3)初始化列表、友元函数、内部类

文章目录 再谈构造函数构造函数体内赋值 初始化列表初始化列表特点 类型转换static成员static特点C11中成员初始化的新用法 友元友元函数友元函数特点 友元类友元类的特点 内部类内部类的特点 再谈构造函数 构造函数体内赋值 当我们创建对象时&#xff0c;编译器会调用构造函…...

CF4C Registration system(哈希实现)

解题思路&#xff1a;因为这道题在每次输入一个字符串后&#xff0c;都需要进行一次查找以判断是否需要按照规则生成新的用户名&#xff0c;故这道题使用STL容器map进行哈希是最合适的(map的查找时间复杂度为log n)&#xff0c;在题目描述中&#xff0c;如果用户名已经被注册&a…...

DDI0487--A1.7

Introduction RAS(Reliability&#xff0c;Availability&#xff0c;Serviceability&#xff09; RAS是衡量一个系统可靠性的三个方面: Reliability——持续提供正确服务的能力。 Availability——正确提供服务的准备状态。 Serviceability——能够进行修改和修复的能力。 R…...

MySQL事务(transaction)(笔记)

事务(Transaction)&#xff08;必须掌握必须理解&#xff09; 1.什么是事务? 一个事务是一个完整的业务逻辑单元&#xff08;一个业务逻辑单元常常涉及到多条DML语句共同执行完成&#xff09;,不可再分&#xff08;最小的工作单元&#xff09; 一个事务就是一个业务,完成一个…...

ADS1299模拟前端(AFE)代替芯片——LHE7909

在现代医疗科技的飞速发展中&#xff0c;精确的生物电势测量设备变得越来越重要。领慧立芯推出的LHE7909&#xff0c;是一款专为心电图&#xff08;ECG&#xff09;和其他生物电势测量设计的低噪声24位模数转换器&#xff08;ADC&#xff09;&#xff0c;为医疗设备制造商提供了…...

(三十二)Android开发中AppCompatActivity和Activity之间的详细区别

在 Android 开发中&#xff0c;AppCompatActivity 和 Activity 是两个核心类&#xff0c;用于创建和管理应用程序的用户界面。尽管它们功能上有重叠&#xff0c;但它们之间存在显著的区别。本文将详细讲解 AppCompatActivity 和 Activity 的区别&#xff0c;并结合代码示例和具…...

Neo4j 的 `SET n += $properties` 语法详解

Neo4j 的 SET n $properties 语法详解 SET n $properties 是 Neo4j Cypher 查询语言中的一个非常有用的语法&#xff0c;用于更新节点或关系的属性。让我详细解释它的含义和工作原理&#xff1a; 基本含义 SET&#xff1a;Cypher 中用于修改属性或标签的关键字n&#xff1…...

springboot 框架把 resources下的zip压缩包, springboot 项目启动后解压到项目根目录工具类

最近有一个需求&#xff0c;在开发的时候 有一些c的扩展文件 需要放到服务器上&#xff0c;如果手动放上去&#xff0c;给用户部署项目就很麻烦&#xff0c;就根据这个需求&#xff0c;先把项目需要的 扩展文件 打包成zip压缩包 然后项目启动的时候 把resources文件夹下的 zip压…...

指针(5)

1.sizeof 和 strlen 的对比 1.1sizeof sizeof 是操作符&#xff0c;sizeof 计算变量所占内存空间的大小&#xff0c;单位是字节&#xff0c;如果操作数是类型的话&#xff0c;计算的是使用类型创建的变量所占空间的大小。 sizeof 只关注占用内存的空间的大小&#xff0c;不在…...

机器学习day4-Knn+交叉验证api练习(预测facebook签到位置)

数据集&#xff1a;FackebookV : 预测 row id&#xff1a;签⼊事件的id x y&#xff1a;坐标 accuracy: 准确度&#xff0c;定位精度 time: 时间戳 place_id: 签到的位置&#xff0c;需要预测的内容 具体步骤&#xff1a; # 1.获取数据集 # 2.基本数据处理 # 2.1 缩⼩数据…...

AI工具 Trae 创建java项目和配置运行环境完整示例

以下是使用字节跳动 Trae IDE 创建 Java 项目并配置运行环境的完整示例,结合其核心功能和搜索结果的实践案例整理: 一、环境准备与安装 下载与安装 访问 Trae 官网 下载 Windows 或 macOS 版本客户端,安装完成后选择中文界面和主题(推荐 Dark/DeepBlue 主题)。首次启动时支…...

【论文_序列转换模型架构_20230802v7】Attention Is All You Need 【Transformer】

https://arxiv.org/abs/1706.03762 20170612 v1 代码实现_notebook ∗Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea. 提出用 self-attention 替代 RNNs&#xff0c;并开始…...

清晰易懂的跨域请求知识——拿捏

1. 什么是跨域请求&#xff1f; 简单来说&#xff1a;当你的 前端网页&#xff08;例如 http://frontend.com&#xff09;通过 JavaScript 调用 后端接口&#xff08;例如 http://backend.com/api&#xff09;时&#xff0c;如果两者的 域名、端口、协议 中任意一项不同&#…...

前端漏洞不扫描理由

漏洞类型豁免理由基于DOM的XSS1.已实施安全加固&#xff1a; 使用encodeURIComponent对URL参数进行编码 对特殊字符(<>“”&)进行HTML实体转义 使用template literal替代字符串拼接 移除了直接操作DOM的不安全写法,二次扫描仍然扫描出来&#xff0c;且修改建议模糊 2…...

论文阅读的三个步骤

论文阅读的三个步骤 方法说明链接&#xff1a;https://www.academia.edu/4907403/How_to_Read_a_Paper 方法框架如下...

Javascript 中的继承?如何实现继承?

一、继承的本质 继承&#xff1a;子对象可以自动拥有父对象的属性和方法&#xff0c;就像孩子继承父母的基因。JavaScript 的继承&#xff1a;通过原型链实现&#xff08;原型和原型链是底层核心&#xff09;。 二、4 种常见继承方式 1. 原型链继承&#xff08;传家宝模式&am…...

深入理解 Linux 权限管理:从基础到进阶

在 Linux 系统中&#xff0c;权限管理是保障系统安全与资源合理分配的核心机制。无论是服务器管理员&#xff0c;还是日常使用 Linux 的开发者&#xff0c;深入掌握权限管理&#xff0c;不仅能避免因权限设置不当导致的数据泄露或系统故障&#xff0c;还能灵活高效地管理各类资…...

第1阶段-前5天-考试题及答案

文章目录 1.1 用户 root 的家目录是哪里?1.2 如何查询 linux 系统 ip 地址?1.3 检查是否可以访问 baidu.com 的命令?1.4 [rootoldboy-c7 /etc/sysconfig/ ]# 说说每一部分含义?1.5 说说 Linux 常见快捷键?(至少 3 个)1.6 Windows 分为 C 盘,D 盘,但是 Linux 一切从 根或/ …...

农村供水智能化远程监控解决方案

农村供水智能化远程监控解决方案 ——基于巨控GRM242Q-4D4I4Q(HE)模块的快速部署方案 一、项目需求与痛点 某西南山区农村供水项目需管理12个分散站点&#xff0c;每个站点包含&#xff1a; 4-20mA模拟量&#xff1a;压力传感器、流量计485通信设备&#xff1a;智能水表&…...

4月29日星期二今日早报简报微语报早读

4月29日星期二&#xff0c;农历四月初二&#xff0c;早报#微语早读。 1、特朗普声称中方领导人打了电话&#xff0c;外交部&#xff1a;近期中美元首没有通话&#xff1b; 2、跳水世界杯总决赛名单出炉&#xff0c;“梦之队”全主力出战&#xff1b; 3、深圳&#xff1a;对年…...

C++日更八股--first

### 内存static和dynamic的区别 static&#xff08;静态&#xff09;​​ 和 ​​dynamic&#xff08;动态&#xff09;<br> static:内存分配在编译的时候确定&#xff0c;大小和生命周期固定&#xff0c;无需运行时分配开销<br> dynamic:内存分配在运行时动态申请…...

Git操作指令

1.基础操作指令: (1).查看修改的状态(git status): 查看修改的状态(暂存区、工作区) (2).添加工作区到暂存区(git add 单个文件名 | 通配符): 添加工作区一个或多个文件的修改到暂存区 (3).提交暂存区到本地仓库(git commit -m "注释内容"): 提交暂存区内容到本…...

Linux——安装NVM

1. 安装命令 官方地址&#xff1a;https://github.com/nvm-sh/nvm curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash2. 安装完成后执行命令 source ~/.bashrc3. 验证 nvm -v...

C++之AVL树

前言 一、AVL的概念 二、AVL树的实现 2.1 AVL的结点结构 2.2 AVL树结点的插入 平衡因子的更新 更新原则&#xff1a; 更新停止的条件&#xff1a; 插入结点以及更新平衡因子的代码实现 旋转 右单旋 左单旋 左右双旋 右左双旋 2.3 AVL树的查找 2.4 AVL树的平衡性检测 总结 前言 …...

解决STM32H743单片机USB_HOST+FATF操作usb文件

前缀 花了两天的时间整理了一下在使用STM32H743单片机开发usb相关功能时遇到的问题及解决方案&#xff0c;具体为以下2种情况&#xff1a; 1.USB插上单片机后&#xff0c;单片机卡死&#xff0c;导致长时间没有喂狗程序重启&#xff1b; 2.USB正常插拔后&#xff0c;使用FAT…...

数据结构|并查集

Hello &#xff01;朋友们&#xff0c;这是我在学习过程中梳理的笔记&#xff0c;以作以后复习回顾&#xff0c;有时略有潦草&#xff0c;一些话是我用自己的话描述的&#xff0c;可能不够准确&#xff0c;还是感谢大家的阅读&#xff01; 目录 一、并查集Quickfind 二、两种算…...

从拒绝采样到强化学习,大语言模型推理极简新路径!

大语言模型&#xff08;LLMs&#xff09;的推理能力是当下研究热点&#xff0c;强化学习在其复杂推理任务微调中广泛应用。这篇论文深入剖析了相关算法&#xff0c;发现简单的拒绝采样基线方法表现惊人&#xff0c;还提出了新算法。快来一探究竟&#xff0c;看看这些发现如何颠…...

数据中心电能质量问题解决方案及经典案例

行业背景与挑战 数据中心作为互联网的核心枢纽&#xff0c;承载着海量数据存储、计算及通信任务&#xff0c;其内部精密设备&#xff08;如恒温恒湿空调、高精度开关电源等&#xff09;对电能质量极为敏感。微小的电压波动或频率偏差可能导致设备损坏&#xff0c;而瞬态过电压…...

【软考-高级】【信息系统项目管理师】【论文基础】沟通管理过程输入输出及工具技术的使用方法

沟通管理概念 沟通是人们分享信息、思想和情感的过程&#xff0c;沟通的主旨在于互动双方建立彼此相互了解的关系&#xff0c;相互回应&#xff0c;并期待能经由沟通的过程相互接纳并达成共识。 沟通失败是很多IT项目失败的重要原因。 与IT项目成功有关的最重要的四个因素是…...

优化PCB Via Stub系列(1):一次学会利用层叠设计降低Via Stub损耗

开路谐振对SI而言真不是个好东西&#xff0c;这种1/4波长谐振会带来讯号的驻波&#xff0c;进而降低整体通道带宽&#xff0c;导致SI不佳&#xff01; 在高速PCB设计中&#xff0c;最常发生的1/4波长谐振就属过孔的Via stub&#xff0c;这个小小的金属残段可以酿成大大的SI问题…...

STP端口状态变迁及故障拓扑变化

STP端口状态变迁及故障拓扑变化 一、STP 端口状态变迁&#xff08;以标准 STP 为例&#xff0c;共 5 种状态&#xff09; 状态功能描述能否收发数据帧能否收发 BPDU持续时间进入条件Disabled端口物理关闭或被管理员手动关闭&#xff0c;不参与 STP 运算。否否-端口物理 down …...

9.idea中创建springboot项目_jdk1.8

9. idea中创建springboot项目_jdk1.8 步骤 1&#xff1a;打开 IntelliJ IDEA 并创建新项目 启动 IntelliJ IDEA。在欢迎界面&#xff0c;点击 New Project&#xff08;或通过菜单栏 File > New > Project&#xff09;。 步骤 2&#xff1a;选择 Maven 项目类型 在左侧…...

mysql 事务中如果有sql语句出错,会导致自动回滚吗?

CREATE TABLE name ( id int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ID, name varchar(32) DEFAULT COMMENT 名称, PRIMARY KEY (id) ) ENGINEInnoDB DEFAULT CHARSETutf8mb4; 情况1.执行下列操作&#xff0c; 会发现新开窗口 去查询name表时&#xff0c;整个事务都…...

考OCM证书前需要有OCP证书

报考OCM认证必须持有有效OCP证书。 从知识体系的构建来看&#xff0c;OCP 和 OCM 认证构成了一个循序渐进的学习和考核体系。OCP 认证侧重于考察数据库管理员和开发人员对 Oracle 数据库的基础架构、日常管理、性能优化、备份恢复等核心技能的掌握。通过 OCP 考试&#xff0c;意…...

动态图表 -- eg1

问题&#xff1a; 前端vue&#xff0c;后端springboot&#xff0c;实现动态表格样式&#xff0c;&#xff08;表格List<Student>&#xff0c;Student类有年级&#xff0c;班级&#xff0c;文理科分类&#xff0c;姓名&#xff0c;学号&#xff0c;等属性。先根据年级分类…...

echo 1 > /proc/sys/kernel/nmi_watchdog报错

报错内容 /proc/sys/kernel/nmi_watchdog报错,内容如下: [root@localhost log]# echo 1 > /proc/sys/kernel/nmi_watchdog -bash: echo: write error: Unknown error 524 [root@localhost log]#报错原因 内核未配置 NMI 支持 某些自定义内核可能未编译 NMI Watchdog 驱…...

upload-labs PASS 1-5通关

PASS-01 前端javascript检查 1&#xff0c;第一个提示javascript对上传的文件进行审查 2&#xff0c;javascript工作在前端页面&#xff0c;可以直接删除具有审查功能的代码 3&#xff0c;删除之后再上传一句话木马 上传成功&#xff0c;可以使用蚁剑进行连接&#xff0c;控制网…...

大数据测试集群环境部署

Hadoop大数据集群搭建&#xff08;超详细&#xff09;_hadoop_小飞飞519-GitCode 开源社区 hadoop集群一之虚拟机安装(mac)_hadoop_皮皮虾不皮呀-华为开发者空间 hadoop集群二之hadoop安装_hadoop_皮皮虾不皮呀-华为开发者空间 虚拟机如何查看gateway | PingCode智库...

BUUCTF——Online Tool

BUUCTF——Online Tool 进入靶场 <?phpif (isset($_SERVER[HTTP_X_FORWARDED_FOR])) {$_SERVER[REMOTE_ADDR] $_SERVER[HTTP_X_FORWARDED_FOR]; }if(!isset($_GET[host])) {highlight_file(__FILE__); } else {$host $_GET[host];$host escapeshellarg($host);$host e…...

人工智能数学基础(三):微积分初步

微积分作为数学的重要分支&#xff0c;为人工智能的发展提供了坚实的理论基础。从理解数据的变化趋势到优化模型参数&#xff0c;微积分的应用贯穿其中。本文将深入探讨微积分的核心概念&#xff0c;并结合 Python 编程实例&#xff0c;助力大家轻松掌握这些关键知识点。资源绑…...

【11408学习记录】考研英语语法核心:倒装句考点全解+真题演练

倒装句 英语语法总结——特殊句式倒装全部倒装介词短语形容词副词There be 部分倒装否定副词或词组位于句首only位于句首虚拟条件句省略if 每日一句词汇第一步&#xff1a;找谓语第二步&#xff1a;断句第三步&#xff1a;简化主句定语从句 英语 语法总结——特殊句式 倒装 …...

云数据中心整体规划方案PPT(113页)

1. 引言 概述&#xff1a;云数据中心整体规划方案旨在构建弹性、高效的云计算基础设施&#xff0c;通过软件定义数据中心&#xff08;SDDC&#xff09;实现资源虚拟化与管理自动化。 2. 技术趋势与背景 技术革新&#xff1a;随着云计算、虚拟化及自动化技术的发展&#xff0c…...

java练习4

创建类对象&#xff0c;要求写一个人的类&#xff0c;内容包括&#xff1a; 值&#xff1a;年龄&#xff0c;姓名&#xff0c;家庭身份 函数&#xff1a;年龄&#xff0c;姓名修改&#xff0c;家庭身份修改&#xff0c;生孩子 package a01_第一次练习.a04_创建类对象;public cl…...

在VMware上创建Ubuntu虚拟机,与Xshell和Xftp的连接和使用

一、在VMware创建Ubuntu虚拟机 1、创建新的虚拟机 2、新建虚拟机安装导向 1&#xff09;自定义安装 2&#xff09;稍后安装操作系统 3&#xff09;选择Linux和Ubuntu64 4&#xff09;可自定义虚拟机名称和虚拟机位置 5&#xff09;选择合适的处理器数量 6&#xff09;虚拟机…...

Java常用注解通俗解释

注解就像是给Java代码贴的"便利贴"&#xff0c;它们不会改变代码本身的逻辑&#xff0c;但能给编译器、开发工具或运行时环境提供额外信息。下面我用最通俗的方式解释Java中最常用的注解&#xff1a; 一、基础篇&#xff1a;人人必知的注解 1. Override - "我…...

前端性能优化2:结合HTTPS与最佳实践,全面优化你的网站性能

点亮极速体验&#xff1a;结合HTTPS与最佳实践&#xff0c;为你详解网站性能优化的道与术 在如今这个信息爆炸、用户耐心极其有限的数字时代&#xff0c;网站的性能早已不是一个可选项&#xff0c;而是关乎生存和发展的核心竞争力。一个迟缓的网站&#xff0c;无异于在数字世界…...

小刚说C语言刷题——1032分糖果

1.题目描述 某幼儿园里&#xff0c;有 5 个小朋友编号为 1&#xff0c;2&#xff0c;3&#xff0c;4&#xff0c;5&#xff0c;他们按自己的编号顺序围坐在一张圆桌旁。他们身上都有若干个糖果&#xff0c;现在他们做一个分糖果游戏。 从 1 号小朋友开始&#xff0c;将他的糖…...