forked from 15921483570/wechat_spider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
56 lines (50 loc) · 1.21 KB
/
handler.go
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
54
55
56
package wechat_spider
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"reflect"
"strings"
"github.com/elazarl/goproxy"
)
var (
Verbose = false
Logger = log.New(os.Stderr, "", log.LstdFlags)
)
func ProxyHandle(proc Processor) func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
return func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if ctx.Req.URL.Path == `/mp/getmasssendmsg` && !strings.Contains(ctx.Req.URL.RawQuery, `f=json`) {
var data []byte
var err error
data, resp.Body, err = copyReader(resp.Body)
if err != nil {
return resp
}
t := reflect.TypeOf(proc)
v := reflect.New(t.Elem())
p := v.Interface().(Processor)
go func() {
err = p.Process(ctx.Req, data)
if err != nil {
Logger.Println(err.Error())
}
p.Output()
}()
}
return resp
}
}
// One of the copies, say from b to r2, could be avoided by using a more
func copyReader(b io.ReadCloser) (bs []byte, r2 io.ReadCloser, err error) {
var buf bytes.Buffer
if _, err = buf.ReadFrom(b); err != nil {
return nil, b, err
}
if err = b.Close(); err != nil {
return nil, b, err
}
return buf.Bytes(), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
}