コード例 #1
0
func TestBuildOutput(t *testing.T) {
	var test_values = []struct {
		iterations int
		expected   string
	}{
		{0, "[]"},
		{1, "[0]"},
		{2, "[0,1]"},
		{10, "[0,1,1,2,3,5,8,13,21,34]"},
	}

	for _, test_val := range test_values {
		fg, err := fibonacci.NewGenerator(test_val.iterations)
		if err != nil {
			t.Errorf("Creating fibonacci generator should not have errored with %d",
				test_val.iterations)
		}
		out_chan := make(chan fibonacci.FibNum)
		go fg.Produce(out_chan)
		output := buildOutput(out_chan)

		if string(output[:]) != test_val.expected {
			t.Errorf("Output from iteration %d did not match.\nExpected\n%s\nGot\n%s\n",
				test_val.iterations, test_val.expected, string(output[:]))
		}
	}
}
コード例 #2
0
// Handler for generating fibonacci numbers, expects a variable n to be set through
// a POST form or query or a GET query value
func (frh *FibonacciRequestHandler) FibonacciRequestHandleFunc(res http.ResponseWriter, req *http.Request) {
	frh.activeReq <- 1
	start := time.Now()
	var stat reqStat
	defer func() {
		frh.activeReq <- -1
		stat.duration = time.Since(start)
		frh.reqStats <- stat
	}()

	// If the path does not match exactly then response with error
	if req.URL.Path != frh.url_path {
		msg := fmt.Sprintf("Request path (%s) does not match %s", req.URL.Path, frh.url_path)
		writeLogMsg("%s, respond with code StatusNotFound", msg)
		http.Error(res, msg, http.StatusNotFound)
		return
	}
	if req.Method != "POST" && req.Method != "GET" {
		respondToUnsupportedMethod(res, req)
		return
	}

	n, err := getIterationCount(req)
	if err != nil {
		http.Error(res, err.Error(), http.StatusBadRequest)
		return
	}

	stat.iterations = n
	fg, err := fibonacci.NewGenerator(n)
	if err != nil {
		http.Error(res, err.Error(), http.StatusBadRequest)
		writeLogMsg("FibonacciGenerator reported %q from request %q", err, req)
		return
	}

	nums := make(chan fibonacci.FibNum)
	go fg.Produce(nums)
	output := buildOutput(nums)

	_, err = res.Write(output)
	if err != nil {
		writeLogMsg("Error (%s) while writing response for %q", err, req.Host)
	}
}