func GetSubmatchAsInt(req *http.Request, n int) (int64, error) {
	sm, err := GetSubmatch(req, n)
	if err != nil {
		return 0, err
	}
	return strconv.ParseInt(sm, 10, 64)
}
GetSubmatchAsInt has to be used in Responders installed by
RegisterRegexpResponder or RegisterResponder + "=~" URL prefix. It
allows to retrieve the n-th submatch of the matching regexp, as an
int64. Example:
RegisterResponder("GET", `=~^/item/id/(\d+)\z`,
func(req *http.Request) (*http.Response, error) {
id, err := GetSubmatchAsInt(req, 1) // 1=first regexp submatch
if err != nil {
return nil, err
}
return NewJsonResponse(200, map[string]interface{}{
"id":   id,
"name": "The beautiful name",
})
})

It panics if n < 1. See MustGetSubmatchAsInt to avoid testing the
returned error.
package httpmock
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"regexp"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync"
)
const regexpPrefix = "=~"
var NoResponderFound = errors.New("no responder found")  
type routeKey struct {
	Method string
	URL    string
}
var noResponder routeKey
func (r routeKey) String() string {
	if r == noResponder {
		return "NO_RESPONDER"
	}
	return r.Method + " " + r.URL
}
func ConnectionFailure(*http.Request) (*http.Response, error) {
	return nil, NoResponderFound
}
func NewMockTransport() *MockTransport {
	return &MockTransport{
		responders:    make(map[routeKey]Responder),
		callCountInfo: make(map[routeKey]int),
	}
}
type regexpResponder struct {
	origRx    string
	method    string
	rx        *regexp.Regexp
	responder Responder
}
type MockTransport struct {
	mu               sync.RWMutex
	responders       map[routeKey]Responder
	regexpResponders []regexpResponder
	noResponder      Responder
	callCountInfo    map[routeKey]int
	totalCallCount   int
}
func (m *MockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	url := req.URL.String()
	method := req.Method
	if method == "" {
		method = http.MethodGet
	}
	var (
		responder  Responder
		respKey    routeKey
		submatches []string
	)
	key := routeKey{
		Method: method,
	}
	for _, getResponder := range []func(routeKey) (Responder, routeKey, []string){
		m.responderForKey,        
		m.regexpResponderForKey,  
	} {
		key.URL = url
		responder, respKey, submatches = getResponder(key)
		if responder != nil {
			break
		}
		query := sortedQuery(req.URL.Query())
		if query != "" {
			key.URL = strings.Replace(url, req.URL.RawQuery, query, 1)
			responder, respKey, submatches = getResponder(key)
			if responder != nil {
				break
			}
		}
		strippedURL := *req.URL
		strippedURL.RawQuery = ""
		strippedURL.Fragment = ""
		surl := strings.TrimSuffix(strippedURL.String(), "?")
		hasQueryString := url != surl
		if hasQueryString {
			key.URL = surl
			responder, respKey, submatches = getResponder(key)
			if responder != nil {
				break
			}
		}
		pathAlone := req.URL.Path
		if hasQueryString {
			key.URL = pathAlone + strings.TrimPrefix(url, surl)  
			responder, respKey, submatches = getResponder(key)
			if responder != nil {
				break
			}
			key.URL = pathAlone + "?" + sortedQuery(req.URL.Query())
			if req.URL.Fragment != "" {
				key.URL += "#" + req.URL.Fragment
			}
			responder, respKey, submatches = getResponder(key)
			if responder != nil {
				break
			}
		}
		key.URL = pathAlone
		responder, respKey, submatches = getResponder(key)
		if responder != nil {
			break
		}
	}
	m.mu.Lock()
	if responder != nil {
		m.callCountInfo[key]++
		if key != respKey {
			m.callCountInfo[respKey]++
		}
		m.totalCallCount++
	} else {
		if m.noResponder != nil {
			m.callCountInfo[noResponder]++
			m.totalCallCount++
			responder = m.noResponder
		}
	}
	m.mu.Unlock()
	if responder == nil {
		return ConnectionFailure(req)
	}
	return runCancelable(responder, setSubmatches(req, submatches))
}
func runCancelable(responder Responder, req *http.Request) (*http.Response, error) {
	ctx := req.Context()
	if req.Cancel == nil && ctx.Done() == nil {  
		resp, err := responder(req)
		return resp, checkStackTracer(req, err)
	}
	type result struct {
		response *http.Response
		err      error
	}
	resultch := make(chan result, 1)
	done := make(chan struct{}, 1)
	go func() {
		select {
		case <-req.Cancel:  
			resultch <- result{
				response: nil,
				err:      errors.New("request canceled"),
			}
		case <-ctx.Done():
			resultch <- result{
				response: nil,
				err:      ctx.Err(),
			}
		case <-done:
		}
	}()
	go func() {
		defer func() {
			if err := recover(); err != nil {
				resultch <- result{
					response: nil,
					err:      fmt.Errorf("panic in responder: got %q", err),
				}
			}
		}()
		response, err := responder(req)
		resultch <- result{
			response: response,
			err:      err,
		}
	}()
	r := <-resultch
	done <- struct{}{}
	return r.response, checkStackTracer(req, r.err)
}
type stackTracer struct {
	customFn func(...interface{})
	err      error
}
func (n stackTracer) Error() string {
	if n.err == nil {
		return ""
	}
	return n.err.Error()
}
func checkStackTracer(req *http.Request, err error) error {
	if nf, ok := err.(stackTracer); ok {
		if nf.customFn != nil {
			pc := make([]uintptr, 128)
			npc := runtime.Callers(2, pc)
			pc = pc[:npc]
			var mesg bytes.Buffer
			var netHTTPBegin, netHTTPEnd bool
			for {
				frames := runtime.CallersFrames(pc)
				var lastFn string
				for {
					frame, more := frames.Next()
					if !netHTTPEnd {
						if netHTTPBegin {
							netHTTPEnd = !strings.HasPrefix(frame.Function, "net/http.")
						} else {
							netHTTPBegin = strings.HasPrefix(frame.Function, "net/http.")
						}
					}
					if netHTTPEnd {
						if lastFn != "" {
							if mesg.Len() == 0 {
								if nf.err != nil {
									mesg.WriteString(nf.err.Error())
								} else {
									fmt.Fprintf(&mesg, "%s %s", req.Method, req.URL)
								}
								mesg.WriteString("\nCalled from ")
							} else {
								mesg.WriteString("\n  ")
							}
							fmt.Fprintf(&mesg, "%s()\n    at %s:%d", lastFn, frame.File, frame.Line)
						}
					}
					lastFn = frame.Function
					if !more {
						break
					}
				}
				if mesg.Len() > 0 {
					break
				}
				netHTTPEnd = true  
			}
			nf.customFn(mesg.String())
		}
		err = nf.err
	}
	return err
}
func (m *MockTransport) responderForKey(key routeKey) (Responder, routeKey, []string) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	return m.responders[key], key, nil
}
func (m *MockTransport) regexpResponderForKey(key routeKey) (Responder, routeKey, []string) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	for _, regInfo := range m.regexpResponders {
		if regInfo.method == key.Method {
			if sm := regInfo.rx.FindStringSubmatch(key.URL); sm != nil {
				if len(sm) == 1 {
					sm = nil
				} else {
					sm = sm[1:]
				}
				return regInfo.responder, routeKey{
					Method: key.Method,
					URL:    regInfo.origRx,
				}, sm
			}
		}
	}
	return nil, key, nil
}
func isRegexpURL(url string) bool {
	return strings.HasPrefix(url, regexpPrefix)
}
func (m *MockTransport) RegisterResponder(method, url string, responder Responder) {
	if isRegexpURL(url) {
		m.registerRegexpResponder(regexpResponder{
			origRx:    url,
			method:    method,
			rx:        regexp.MustCompile(url[2:]),
			responder: responder,
		})
		return
	}
	key := routeKey{
		Method: method,
		URL:    url,
	}
	m.mu.Lock()
	m.responders[key] = responder
	m.callCountInfo[key] = 0
	m.mu.Unlock()
}
func (m *MockTransport) registerRegexpResponder(regexpResponder regexpResponder) {
	m.mu.Lock()
	defer m.mu.Unlock()
found:
	for {
		for i, rr := range m.regexpResponders {
			if rr.method == regexpResponder.method && rr.origRx == regexpResponder.origRx {
				m.regexpResponders[i] = regexpResponder
				break found
			}
		}
		m.regexpResponders = append(m.regexpResponders, regexpResponder)
		break  
	}
	m.callCountInfo[routeKey{
		Method: regexpResponder.method,
		URL:    regexpResponder.origRx,
	}] = 0
}
func (m *MockTransport) RegisterRegexpResponder(method string, urlRegexp *regexp.Regexp, responder Responder) {
	m.registerRegexpResponder(regexpResponder{
		origRx:    regexpPrefix + urlRegexp.String(),
		method:    method,
		rx:        urlRegexp,
		responder: responder,
	})
}
func (m *MockTransport) RegisterResponderWithQuery(method, path string, query interface{}, responder Responder) {
	if isRegexpURL(path) {
		panic(`path begins with "=~", RegisterResponder should be used instead of RegisterResponderWithQuery`)
	}
	var mapQuery url.Values
	switch q := query.(type) {
	case url.Values:
		mapQuery = q
	case map[string]string:
		mapQuery = make(url.Values, len(q))
		for key, e := range q {
			mapQuery[key] = []string{e}
		}
	case string:
		var err error
		mapQuery, err = url.ParseQuery(q)
		if err != nil {
			panic("RegisterResponderWithQuery bad query string: " + err.Error())
		}
	default:
		if query != nil {
			panic(fmt.Sprintf("RegisterResponderWithQuery bad query type %T. Only url.Values, map[string]string and string are allowed", query))
		}
	}
	if queryString := sortedQuery(mapQuery); queryString != "" {
		path += "?" + queryString
	}
	m.RegisterResponder(method, path, responder)
}
func sortedQuery(m url.Values) string {
	if len(m) == 0 {
		return ""
	}
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	var b bytes.Buffer
	var values []string  
	for _, k := range keys {
		values = append(values, m[k]...)
		sort.Strings(values)
		k = url.QueryEscape(k)
		for _, v := range values {
			if b.Len() > 0 {
				b.WriteByte('&')
			}
			fmt.Fprintf(&b, "%v=%v", k, url.QueryEscape(v))
		}
		values = values[:0]
	}
	return b.String()
}
func (m *MockTransport) RegisterNoResponder(responder Responder) {
	m.mu.Lock()
	m.noResponder = responder
	m.mu.Unlock()
}
func (m *MockTransport) Reset() {
	m.mu.Lock()
	m.responders = make(map[routeKey]Responder)
	m.regexpResponders = nil
	m.noResponder = nil
	m.callCountInfo = make(map[routeKey]int)
	m.totalCallCount = 0
	m.mu.Unlock()
}
func (m *MockTransport) GetCallCountInfo() map[string]int {
	res := make(map[string]int, len(m.callCountInfo))
	m.mu.RLock()
	for k, v := range m.callCountInfo {
		res[k.String()] = v
	}
	m.mu.RUnlock()
	return res
}
func (m *MockTransport) GetTotalCallCount() int {
	m.mu.RLock()
	count := m.totalCallCount
	m.mu.RUnlock()
	return count
}
var DefaultTransport = NewMockTransport()
var InitialTransport = http.DefaultTransport
var oldClients = map[*http.Client]http.RoundTripper{}
func Activate() {
	if Disabled() {
		return
	}
	if http.DefaultTransport != DefaultTransport {
		InitialTransport = http.DefaultTransport
	}
	http.DefaultTransport = DefaultTransport
}
func ActivateNonDefault(client *http.Client) {
	if Disabled() {
		return
	}
	if _, ok := oldClients[client]; !ok {
		oldClients[client] = client.Transport
	}
	client.Transport = DefaultTransport
}
func GetCallCountInfo() map[string]int {
	return DefaultTransport.GetCallCountInfo()
}
func GetTotalCallCount() int {
	return DefaultTransport.GetTotalCallCount()
}
func Deactivate() {
	if Disabled() {
		return
	}
	http.DefaultTransport = InitialTransport
	for oldClient, oldTransport := range oldClients {
		oldClient.Transport = oldTransport
		delete(oldClients, oldClient)
	}
}
func Reset() {
	DefaultTransport.Reset()
}
func DeactivateAndReset() {
	Deactivate()
	Reset()
}
func RegisterResponder(method, url string, responder Responder) {
	DefaultTransport.RegisterResponder(method, url, responder)
}
func RegisterRegexpResponder(method string, urlRegexp *regexp.Regexp, responder Responder) {
	DefaultTransport.RegisterRegexpResponder(method, urlRegexp, responder)
}
func RegisterResponderWithQuery(method, path string, query interface{}, responder Responder) {
	DefaultTransport.RegisterResponderWithQuery(method, path, query, responder)
}
func RegisterNoResponder(responder Responder) {
	DefaultTransport.RegisterNoResponder(responder)
}
type submatchesKeyType struct{}
var submatchesKey submatchesKeyType
func setSubmatches(req *http.Request, submatches []string) *http.Request {
	if len(submatches) > 0 {
		return req.WithContext(context.WithValue(req.Context(), submatchesKey, submatches))
	}
	return req
}
var ErrSubmatchNotFound = errors.New("submatch not found")
func GetSubmatch(req *http.Request, n int) (string, error) {
	if n <= 0 {
		panic(fmt.Sprintf("getting submatches starts at 1, not %d", n))
	}
	n--
	submatches, ok := req.Context().Value(submatchesKey).([]string)
	if !ok || n >= len(submatches) {
		return "", ErrSubmatchNotFound
	}
	return submatches[n], nil
}