Package Main
Import (
"Bufio"
"Bytes"
"Encoding/hex"
"FMT"
"Github.com/buger/goreplay/proto"
"OS"
)
RequestID-Originaltoken
var originaltokens map[string][]byte
Originaltoken-Replayedtoken
var tokenaliases map[string][]byte
Func Main () {
Originaltokens = Make (Map[string][]byte)
Tokenaliases = Make (Map[string][]byte)
scanner := bufio.NewScanner(os.Stdin)for scanner.Scan() { encoded := scanner.Bytes() buf := make([]byte, len(encoded)/2) hex.Decode(buf, encoded) process(buf)}
}
Func process (buf []byte) {
First byte indicate payload type, possible values:
1-request
2-response
3-replayedresponse
Payloadtype: = buf[0]
Headersize: = bytes. Indexbyte (buf, ' \ n ') + 1
Header: = Buf[:headersize-1]
Header contains space separated values Of:request type, request ID, and request start time (or round-trip time for Res ponses) Meta: = bytes. Split (header, []byte ("))//For each request should receive 3 payloads (request, response, replayed response) with SA Me request Idreqid: = string (meta[1]) Payload: = Buf[headersize:]debug ("Received Payload:", String (BUF)) switch Payloadtype {case ' 1 '://Request if bytes. Equal (Proto. Path (payload), []byte ("/token")) {originaltokens[reqid] = []byte{} Debug ("Found token Request:", ReqID) } else {token, VS, _: = Proto. Pathparam (Payload, []byte ("token")///token value to production server if vs! =-1 {//If there is GET token param if Alia S, OK: = tokenaliases[string (token)]; OK {//check if the token value to be replaced exists//Rewrite original token to alias payload = Proto. Setpathparam (Payload, []byte ("token"), alias)//Replace the production token with the token of the test suit//Copy modified payload to our buffer Buf= Append (Buf[:headersize], payload ...) }}}//emitting data back OS. Stdout.write (Encode (BUF))//rewrite request ready to be sent to test server case ' 2 '://Original Response If _, OK: = Originaltokens[reqid]; OK {//Token is inside response body securetoken: = Proto. Body (payload)//Fetch the token value returned from the production server originaltokens[reqid] = Securetoken Debug ("Remember origial token:", Strin G (Securetoken))}case ' 3 '://replayed response if originaltoken, OK: = Originaltokens[reqid]; OK {Delete (originaltokens, ReqID) Securetoken: = Proto. Body (payload) tokenaliases[string (originaltoken)] = securetoken//The token value of the test server is used to replace the token value of the positive service Debug ("Create Alias for new token token, is: ", String (Originaltoken)," Now: ", String (Securetoken)}}
}
Func encode (buf []byte) []byte {
DST: = Make ([]byte, Len (buf) *2+1)
Hex. Encode (DST, buf)
Dst[len (DST)-1] = ' \ n '
return dst
}
Func Debug (args ... interface{}) {
Fmt. Fprint (OS. Stderr, "[Debug][token-mod]")
Fmt. Fprintln (OS. Stderr, args ...)
}