golang工具库

发起GET,POST请求

package main

import (
        "time"
        "fmt"
        "bytes"
        "io/ioutil"
        "net/http"
        "encoding/json"
)

type LvsbackendToken struct {
    Code  int
    Msg  string
    Data  Tokenbody    `json:data`
}
type Tokenbody struct {
    Token  string  `json:token`
}
//发送get请求
func get_lvsbackend_token() (token string) {
    url := "http://192.168.1.64/auth?username=mo"
    resp, err := http.Get(url)
    if err != nil {
        fmt.Println(err)
    }
    body, _ := ioutil.ReadAll(resp.Body)
    var data LvsbackendToken //解析interface格式字典数据,需声明结构体Unmarshal后访问内容
    json.Unmarshal(body, &data)
    return data.Data.Token

}

type Warndata struct {
        Touser                   string            `json:"touser"`
        Togroup                  string            `json:"togroup"`
        Msgtype                  string            `json:"msgtype"`
        Agentid                  int               `json:"agentid"`
        Text                     map[string]string `json:"text"`
        Safe                     int               `json:"safe"`
        Enable_id_trans          int               `json:"enable_id_trans"`
        Enable_duplicate_check   int               `json:"enable_duplicate_check"`
        Duplicate_check_interval int               `json:"duplicate_check_interval"`
}
//发送post json请求
func PostMsg(lvstoken string) {
    url := fmt.Sprintf("http://192.168.1.64/api/warn?token=%s", lvstoken)
    var wdata Warndata
    var ct =map[string]string{"content": "9911 test"}
    wdata.Touser = "zz"
    wdata.Msgtype = "text"
    wdata.Agentid = 1002
    wdata.Text = ct

    jsonStr, _ := json.Marshal(wdata)   //Marshal一个struct数据
    //fmt.Println(string(jsonStr))
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    if err != nil {
        panic(err)
    }
    defer req.Body.Close()
    client := &http.Client{Timeout: 5 * time.Second}
    resp, error := client.Do(req)
    if error != nil {
        panic(error)
    }
    defer resp.Body.Close()
    result, _ := ioutil.ReadAll(resp.Body)  //读取body内容
    rep := string(result)
    fmt.Println(rep)
}

func main() {
  tkstr := get_lvsbackend_token()
  PostMsg(tkstr)
}

你可能感兴趣的:(golang工具库)