doutao4480 2018-11-11 13:59
浏览 818

在字符串中插入变量

I have the hostname and a json formated string. I want to insert the hostname inside the value string of a key in that json formated string.

My full code:

func pager() string {
token := "xxxxxxxxxxx"
url := "https://api.pagerduty.com/incidents"
hostname, err := os.Hostname()
fmt.Println(hostname, err)

jsonStr := []byte(`{
    "incident": {
        "type": "incident",
        **"title": "Docker is down on."+hostname,**
        "service": {
          "id": "PWIXJZS",
          "type": "service_reference"
        },
        "priority": {
          "id": "P53ZZH5",
          "type": "priority_reference"
        },
        "urgency": "high",
        "incident_key": "baf7cf21b1da41b4b0221008339ff357",
        "body": {
          "type": "incident_body",
          "details": "A disk is getting full on this machine. You should investigate what is causing the disk to fill, and ensure that there is an automated process in place for ensuring data is rotated (eg. logs should have logrotate around them). If data is expected to stay on this disk forever, you should start planning to scale up to a larger disk."
        },
        "escalation_policy": {
          "id": "PT20YPA",
          "type": "escalation_policy_reference"
        }
    }
}`)

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/vnd.pagerduty+json;version=2")
req.Header.Set("From", "shinoda@wathever.com")
req.Header.Set("Authorization", "Token token="+token)

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    panic(err)
}

return resp.Status
}

func main() {
    fmt.Println(pager())

}

I am not very familiar with go, in python I can do this easily and I dont know the proper way to do this in golang.

If someone could explain me, I would be grateful.

thanks in advance.

  • 写回答

4条回答 默认 最新

  • duanla1996 2018-11-11 14:37
    关注

    make a struct in go to represent the json

    type 
        Incident struct {
            Type    string `json:"type"`
            Title   string `json:"title"`
            Service struct {
                ID   string `json:"id"`
                Type string `json:"type"`
            } `json:"service"`
            Priority struct {
                ID   string `json:"id"`
                Type string `json:"type"`
            } `json:"priority"`
            Urgency     string `json:"urgency"`
            IncidentKey string `json:"incident_key"`
            Body        struct {
                Type    string `json:"type"`
                Details string `json:"details"`
            } `json:"body"`
            EscalationPolicy struct {
                ID   string `json:"id"`
                Type string `json:"type"`
            } `json:"escalation_policy"`
    }
    

    then do something like

    hostname,err:=os.Hostname()
    if (err !=nil) {
       panic(err)
    }
    incident:=Incident{ Type: "incident",
                        Title: fmt.Sprintf("Docker is down on %s", hostname),
                        //...etc etc add all other fields
    
    req, err := http.NewRequest("POST", url, json.Marshal(incident))
    

    The workaround for declaring structs inside structs seems a bit clumsy (sorry)

    Service: struct {
                ID   string `json:"id"`
                Type string `json:"type"`
            }{
                ID: "asdf",
                Type: "ABC",
           },
    

    This other answer https://stackoverflow.com/a/53255390/1153938 shows how to split the structs inside the Incident struct and is a cleaner way of doing it

    I'll leave this answer here because it might be of interest how to declare it in this way

    If you are only calling json.Unmarshal then this way would be fine but for declaring stuff in a program as you need to do, perhaps not the best

    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch