0%

Golang 常用定时任务

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

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

type Resp struct {
Status string `json:"status"`
Message interface{} `json:"message"`
}

type Req struct {
Name string `json:"name"`
Age int `json:"age"`
}

func RequestExample(request Req) (*Resp, error) {
httpClient := &http.Client{}
httpClient.Timeout = 5 * time.Second
jsonValue, err := json.Marshal(request)
req, err := http.NewRequest("POST", "http://127.0.0.1/test", bytes.NewBuffer(jsonValue))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()

responseData, _ := ioutil.ReadAll(resp.Body)
dat := Resp{}
if err := json.Unmarshal(responseData, &dat); err != nil {
log.Println("failed to load json")
}
return &dat, nil
}

func main() {
req := Req{Name: "Bob", Age: 30}
resp, err := RequestExample(req)
if err != nil {
return
}
fmt.Println(resp)
}

grinning all the time

😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄 😄