예제 #1
0
func (middleware *offlinemiddleware) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	newbody := make([]byte, req.ContentLength)
	req.Body.Read(newbody)
	path := strings.Split(req.RequestURI, "?")

	log.Println("try to get ", path[0], req.Method, string(newbody))
	if path[0] == "/json" {
		middleware.GenerateJSON(w)
		return
	} else if path[0] == "/pact" {
		middleware.GeneratePACT(w)
		return
	} else if path[0] == "/truncate" {
		middleware.Truncate(w)
		return
	}

	res, err := middleware.replaydb.GetResponse(path[0], req.Method, string(newbody))
	if err != nil || res == nil {
		log.Println("Cannot get response from replaydb on offline mode, need hanle in offline handler ", err)
		newRq, err := http.NewRequest(req.Method, req.RequestURI, ioutil.NopCloser(bytes.NewReader(newbody)))
		if err != nil {
			log.Println("new http request failed ", err)
		}
		middleware.router.ServeHTTP(w, newRq)
	} else {
		result, _ := utils.TOJsonInterface(res)
		log.Println("Get response from replaydb on offline mode ", (result))
		resultmap := result.(map[string]interface{})
		for key, value := range resultmap {
			status, _ := strconv.Atoi(key)
			w.WriteHeader(status)
			stream := []byte("")
			if value != nil {
				stream, err = json.Marshal(value)
				if err != nil {
					log.Println("Marshal failed ", err, stream)
				}
			}
			_, err = w.Write(stream)
			if err != nil {
				log.Println("Get response from replaydb  but write error ", err)
			}
			break
		}
	}
}
예제 #2
0
func (replay *ReplayDB) ReadJsonFiles(filePath string) {
	now := time.Now()
	log.Println("going to read file", filePath)
	stream, err := ioutil.ReadFile(filePath)
	if err != nil {
		log.Println("going to read file error happened ", err, stream)
		return
	}

	res, err := utils.TOJsonInterface(stream)
	paths := res.(map[string]interface{})["paths"]
	pathsMap := paths.(map[string]interface{})
	for path, val := range pathsMap {
		valMap := val.(map[string]interface{})
		for method, detail := range valMap {
			detailMap := detail.([]interface{})
			for _, detailMapel := range detailMap {
				detailMapItem := detailMapel.(map[string]interface{})
				request, ok := detailMapItem["request"]
				if !ok {
					log.Println("missing request, continue ", detailMapItem)
					continue
				}
				respose, ok := detailMapItem["response"]
				if !ok {
					log.Println("missing response, continue ", detailMapItem)
					continue
				}
				responseMap := respose.(map[string]interface{})
				for k, v := range responseMap {
					status, _ := strconv.Atoi(k)
					//fmt.Println("\r\nstore:", request, "response", v)
					replay.StoreRequestFromJson(path, method, request, v, status)
					break
				}
			}
		}
	}
	log.Println("Time Used:", time.Since(now))
}