|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "net/http" |
| 8 | + "time" |
| 9 | + "github.com/astaxie/beego/logs" |
| 10 | +) |
| 11 | + |
| 12 | +var plainContentType = []string{"text/plain; charset=utf-8"} |
| 13 | + |
| 14 | +func init() { |
| 15 | + logs.SetLogger(logs.AdapterFile, `{"filename":"logs/replay.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10}`) |
| 16 | + logs.Async() |
| 17 | +} |
| 18 | + |
| 19 | +// 返回内容 |
| 20 | +func writeContextType(w http.ResponseWriter, value []string) { |
| 21 | + header := w.Header() |
| 22 | + if val := header["Content-Type"]; len(val) == 0 { |
| 23 | + header["Content-Type"] = value |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +// 获取发送内容 |
| 28 | +func getBody(w http.ResponseWriter, r *http.Request) { |
| 29 | + defer r.Body.Close() |
| 30 | + con, _ := ioutil.ReadAll(r.Body) // 获取post的数据 |
| 31 | + reqUrl := r.RequestURI |
| 32 | + bodyStr := string(con) // 发送的XML内容 |
| 33 | + logs.Info(r.RequestURI, "接收到内容:", bodyStr) |
| 34 | + // 请求转发 |
| 35 | + contentReader := bytes.NewReader(con) |
| 36 | + reqResByte := make(chan []byte, 1) |
| 37 | + startTime := time.Now().UnixNano() |
| 38 | + go func() { |
| 39 | + // 处理请求 |
| 40 | + req, _ := http.NewRequest("POST", "http://172.16.50.131:3040"+reqUrl, contentReader) |
| 41 | + req.Header.Set("Content-Type", "application/xml") |
| 42 | + client := &http.Client{} |
| 43 | + client.Timeout = 10 * time.Second |
| 44 | + resp, _ := client.Do(req) |
| 45 | + defer resp.Body.Close() |
| 46 | + // 获取返回内容返回 |
| 47 | + reqRes, _ := ioutil.ReadAll(resp.Body) // 获取post的数据 |
| 48 | + logs.Info("返回到内容:", string(reqRes)) |
| 49 | + logs.Info("处理耗时:", time.Now().UnixNano()-startTime) |
| 50 | + reqResByte <- reqRes |
| 51 | + }() |
| 52 | + // 返回 |
| 53 | + writeContextType(w, plainContentType) |
| 54 | + w.Write(<-reqResByte) |
| 55 | +} |
| 56 | + |
| 57 | +func main() { |
| 58 | + // 正式上线地址 |
| 59 | + http.HandleFunc("/wxReply", getBody) |
| 60 | + fmt.Println("soft start") |
| 61 | + http.ListenAndServe(":8400", nil) |
| 62 | +} |
0 commit comments