Ejemplo n.º 1
0
//SendMockResponse sending a response based on a mock.
func (h *Mockhandler) SendMockResponse(m *model.MockConf, w http.ResponseWriter, r *http.Request) {
	filename := h.DataDirPath + "/" + model.GetMockFileName(r) + filesys.ContentEXT
	dr, err := h.Fs.ReadResource(filename) //ioutil.ReadFile(filename)
	if err != nil {
		log.Printf("%s \n", err)
		http.Error(w, "Resource unavailable: "+r.URL.String()+" Failed with error: "+err.Error(), http.StatusServiceUnavailable)
		return
	}
	d, err := ioutil.ReadAll(dr)
	if err != nil {
		log.Printf("%s \n", err)
		http.Error(w, "Resource unavailable: "+r.URL.String()+" Failed with error: "+err.Error(), http.StatusServiceUnavailable)
		return
	}

	w.Header().Set("Content-Length", strconv.FormatInt(int64(len(d)), 10)) //strconv.FormatInt(dstat.Size(), 10))
	w.Header().Set("Content-Type", m.ContentType)
	w.WriteHeader(m.StatusCode)
	w.Write(d)
	log.Printf("%v \t %s \t %v bytes\n", m.StatusCode, r.URL.String(), len(d))

	wsmsg, err := json.Marshal(m)
	if err != nil {
		log.Printf("Websocket error: %s \n", err)
		return
	}
	msg := ws.Message{Data: wsmsg}
	h.WSMockInfoHandler.Send(&msg)
}
Ejemplo n.º 2
0
func TestGetMockFileName_ShouldReturnFilename(t *testing.T) {
	//Equals to base 32 uri = / method = GET
	expectedFilename := "AZH5Y2SPPMLFNUGNVXRJGON64IUV3FNB"
	req, err := http.NewRequest("GET", "http://myservice.com/", strings.NewReader(string("body")))
	if err != nil {
		t.Errorf("%v", err)
	}
	got := model.GetMockFileName(req)

	if got != expectedFilename {
		t.Errorf("Expected: %v but got: %v", expectedFilename, got)
	}
}
Ejemplo n.º 3
0
func (h *Mockhandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	mConfFileName := h.DataDirPath + "/" + model.GetMockFileName(r) + filesys.ConfEXT
	m, err := h.Fs.ReadMockConf(mConfFileName)
	if err != nil {
		if r.Method != "GET" {
			body := "Mock only executes GET requests. " + r.URL.String() + "\n" + r.Method + " is faked and can be edited in mock GUI. see /mock"
			m = &model.MockConf{URI: r.URL.RequestURI(), Method: r.Method, StatusCode: http.StatusOK}
			err := h.Fs.WriteMock(*m, []byte(body), h.DataDirPath)
			if err != nil {
				http.Error(w, "Error occured when requesting: "+r.URL.String()+" Failed with error: "+err.Error(), http.StatusInternalServerError)
			}
		} else {
			//do real request do targetet system, to retrive information from system.
			m, err = h.requestInfo(w, r)
			if err != nil {
				http.Error(w, "Resource unavailable: "+r.URL.String()+" Failed with error: "+err.Error(), http.StatusInternalServerError)
				return
			}
		}
	}

	h.SendMockResponse(m, w, r)
}