Beispiel #1
1
func TestWithRoutes(t *testing.T) {
	t.Parallel()
	assert := assert.New(t)
	rtes := sampleRoutes()
	server := mockserver.WithRoutes(rtes)
	defer server.Close()
	// Check 404 route
	resp, err := http.Get(server.URL + "/random")
	assert.NoError(err)
	assert.Equal(404, resp.StatusCode)
	// check POST
	resp, err = http.Post(server.URL+"/welcome/tony", "plain/text", bytes.NewBuffer([]byte{}))
	assert.NoError(err)
	assert.Equal(200, resp.StatusCode)
	// check body response
	body, err := parseResp(resp.Body)
	assert.NoError(err)
	assert.Equal(body, "Welcome tony")
	// check 405
	resp, err = http.Get(server.URL + "/welcome/tony")
	assert.NoError(err)
	assert.Equal(405, resp.StatusCode)

	// check second route
	resp, err = http.Get(server.URL + "/hello/world")
	assert.NoError(err)
	assert.Equal(200, resp.StatusCode)
	// check hello world
	body, err = parseResp(resp.Body)
	assert.NoError(err)
	assert.Equal("Hello world", body)
}
Beispiel #2
1
func loadRemoteFeedList(input string) []string {
	feeds := []string{}
	switch path.Ext(input) {
	case ".opml":
		opml := OPML{}
		resp, err := http.Get(input)
		if err != nil {
			logger.Fatal("couldn't load feed list: %v", err)
		}
		decoder := xml.NewDecoder(resp.Body)
		decoder.CharsetReader = charset.NewReader
		decoder.Decode(&opml)
		for _, outline := range opml.Body.Outlines {
			if outline.XmlUrl != "" {
				feeds = append(feeds, outline.XmlUrl)
			}
		}
	case ".txt", ".yaml":
		resp, err := http.Get(input)
		if err != nil {
			logger.Fatal("couldn't load feed list: %v", err)
		}
		data, _ := ioutil.ReadAll(resp.Body)
		yaml.Unmarshal(data, &feeds)
	}
	return feeds
}
Beispiel #3
1
func TestGetContact(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(addressBookHandler))
	defer ts.Close()

	contacts = []contact.Contact{
		contact.Contact{
			Name:  "Kotchaphan",
			Tel:   "000",
			Email: "*****@*****.**",
		},
	}
	resp, _ := http.Get(ts.URL + "/contacts?name=Kotchaphan")
	if resp.StatusCode != http.StatusOK {
		t.Error("Expect status is 200")
	}

	b, _ := ioutil.ReadAll(resp.Body)
	if string(b) != `{"name":"Kotchaphan","tel":"000","email":"*****@*****.**"}`+"\n" {
		t.Error(`Expect json {"name" : "Kotchaphan" , "tel" : "000" , "email" : "*****@*****.**"} but got `, string(b))
	}

	resp, _ = http.Get(ts.URL + "/contacts?name=haha")
	if resp.StatusCode != http.StatusNotFound {
		t.Error("Expect status code is 404")
	}
}
Beispiel #4
1
func Test_Routing(t *testing.T) {
	a := assert.New(t)

	ts := httptest.NewServer(NewMux())
	defer ts.Close()

	res, err := http.Get(ts.URL + "/users")
	a.NoError(err)
	body, err := ioutil.ReadAll(res.Body)
	a.Equal(string(body), "Users Index")

	res, err = http.Get(ts.URL + "/users/42")
	a.NoError(err)
	body, err = ioutil.ReadAll(res.Body)
	a.Equal(string(body), "Users Show: 42")

	res, err = http.Post(ts.URL+"/users/", "plain/text", strings.NewReader("Hello!"))
	a.NoError(err)
	body, err = ioutil.ReadAll(res.Body)
	a.Equal(string(body), "Users Create: Hello!")

	res, err = http.Get(ts.URL + "/posts")
	a.NoError(err)
	body, err = ioutil.ReadAll(res.Body)
	a.Equal(string(body), "POSTS!")
}
func TestAPIGroupMissing(t *testing.T) {
	indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})
	handler := &apiGroupHandler{
		lister:    listers.NewAPIServiceLister(indexer),
		groupName: "foo",
	}

	server := httptest.NewServer(handler)
	defer server.Close()

	resp, err := http.Get(server.URL + "/apis/groupName/foo")
	if err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != http.StatusNotFound {
		t.Fatalf("expected %v, got %v", resp.StatusCode, http.StatusNotFound)
	}

	// foo still has no api services for it (like it was deleted), it should 404
	resp, err = http.Get(server.URL + "/apis/groupName/")
	if err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != http.StatusNotFound {
		t.Fatalf("expected %v, got %v", resp.StatusCode, http.StatusNotFound)
	}
}
Beispiel #6
1
func fetch() []string {

	var server string = "https://raw.githubusercontent.com/roypur/hosts/master/src"

	resp, _ := http.Get(server)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	src := strings.Split(strings.TrimSpace(string(body)), "\n")

	requestData := []string{}

	var j int = len(src) - 1

	for i := 0; i <= j; i++ {
		resp, _ := http.Get(src[i])
		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)

		requestData = append(requestData, string(body))
	}

	var appendString string = strings.Join(requestData, "\n")

	retVal := strings.Split(appendString, "\n")

	return retVal
}
Beispiel #7
0
func TestServerData(t *testing.T) {
	s := startTestServer(t)
	s.putData("hello", []byte("world"))
	resp, err := http.Get(fmt.Sprintf("http://localhost:%d/hello", s.port))
	if err != nil {
		t.Errorf("failed to get 'hello': %v", err)
	}
	b, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		t.Errorf("error while reading data: %v", err)
	}
	if string(b) != "world" {
		t.Errorf("expected %q, got %q", "world", b)
	}

	s.rmData("hello")
	resp, err = http.Get(fmt.Sprintf("http://localhost:%d/hello", s.port))
	if err != nil {
		t.Errorf("unexpected error requesting 'hello': %v", err)
	}
	if resp.StatusCode == http.StatusOK {
		t.Errorf("expected non-OK status after removing 'hello'")
	}
	s.s.Stop()
}
func TestMain(t *testing.T) {
	mux := NewServer()
	ts := httptest.NewServer(mux)
	defer ts.Close()

	res, err := http.Get(ts.URL)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, http.StatusBadRequest, res.StatusCode)

	res, err = http.Get(ts.URL + "/A")
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, http.StatusBadRequest, res.StatusCode)

	res, err = http.Get(ts.URL + "/A/B")
	if err != nil {
		t.Fatal(err)
	}

	res, err = http.Get(ts.URL + "/A/B/URL")
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, http.StatusOK, res.StatusCode)
}
func main() {
	r, err := http.Get("http://mattfarina.com")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer r.Body.Close()
	o, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println(string(o))

	r2, err := http.Get("http://mattfarina.com/about")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer r2.Body.Close()
	o, err = ioutil.ReadAll(r2.Body)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println(string(o))
}
Beispiel #10
0
func TestMockTransport(t *testing.T) {
	Activate(&http.DefaultTransport)
	defer Deactivate()

	url := "https://github.com/"
	body := "hello world"

	RegisterResponder("GET", url, NewStringResponder(200, body))

	resp, err := http.Get(url)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatal(err)
	}

	if string(data) != body {
		t.FailNow()
	}

	// the http client wraps our NoResponderFound error, so we just try and match on text
	if _, err := http.Get(testUrl); !strings.Contains(err.Error(),
		NoResponderFound.Error()) {

		t.Fatal(err)
	}
}
Beispiel #11
0
func TestMockTransportNoResponder(t *testing.T) {
	Activate(&http.DefaultTransport)
	defer DeactivateAndReset()

	Reset()

	if DefaultTransport.noResponder != nil {
		t.Fatal("expected noResponder to be nil")
	}

	if _, err := http.Get(testUrl); err == nil {
		t.Fatal("expected to receive a connection error due to lack of responders")
	}

	RegisterNoResponder(NewStringResponder(200, "hello world"))

	resp, err := http.Get(testUrl)
	if err != nil {
		t.Fatal("expected request to succeed")
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatal(err)
	}

	if string(data) != "hello world" {
		t.Fatal("expected body to be 'hello world'")
	}
}
Beispiel #12
0
func TestServerGracefulStopKeepAlive(t *testing.T) {
	s := NewServer(
		"127.0.0.1:0",
		http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
			w.WriteHeader(http.StatusNoContent)
		}),
	)
	l, err := net.Listen("tcp", s.Addr)
	if nil != err {
		t.Fatal(err)
	}
	go s.Serve(l)
	if _, err := http.Get(fmt.Sprintf("http://%s", l.Addr())); nil != err {
		t.Fatal(err)
	}
	then := time.Now()
	s.Close()
	now := time.Now()
	if then.Add(510 * time.Millisecond).Before(now) {
		t.Fatal("connection not closed quickly")
	}
	if _, err := http.Get(fmt.Sprintf("http://%s", l.Addr())); nil == err {
		t.Fatal("GET / should have failed after server stopped")
	}
}
Beispiel #13
0
func TestFlashes(t *testing.T) {
	resp, err := http.Get("http://localhost:8082/test/flash/")
	if err != nil {
		t.Errorf("%s", err.Error())
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("%s", err.Error())
	}

	if string(body) != "static" {
		t.Errorf("Body:%s:", body)
	}
	resp, err = http.Get("http://localhost:8082/test/flash/")
	if err != nil {
		t.Errorf("%s", err.Error())
	}
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("%s", err.Error())
	}

	if string(body) != "static" {
		t.Errorf("Body:%s:", body)
	}
}
Beispiel #14
0
// Testailee vain latautuuko sivu.
func TestCount(t *testing.T) {
	var res *http.Response
	var got []byte
	var err error

	ts := httptest.NewServer(http.DefaultServeMux)
	defer ts.Close()
	for i := 0; i < 10170; i++ {
		res, _ := http.Get(ts.URL + "/count")
		res.Body.Close()
	}
	if res, err = http.Get(ts.URL + "/count"); err != nil {
		t.Fatal(err)
	}
	if res.StatusCode != 200 {
		t.Error("Status code:", res.StatusCode)
	}
	if got, err = ioutil.ReadAll(res.Body); err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(string(got), "Laskuri: 10171") {
		t.Fatalf("Expected count to be 10171. This is what we got:\n%s", string(got))
	}

}
Beispiel #15
0
func fetchEdges(offset int, limit int, channel chan<- []Edge) {
	var edges []Edge
	done, url := false, fmt.Sprintf(
		"http://localhost:8080/api/graph?offset=%d&limit=%d",
		offset, limit)
	for resp, err := http.Get(url); !done; resp, err = http.Get(url) {
		if err != nil {
			fmt.Println(err.Error())
			os.Exit(0)
		}
		done = func() bool {
			defer resp.Body.Close()
			if resp.StatusCode == 200 {
				body, err := ioutil.ReadAll(resp.Body)
				if err != nil {
					fmt.Println(err.Error())
					os.Exit(0)
				}
				err = json.Unmarshal(body, &edges)
				if err != nil {
					fmt.Println(err.Error())
					os.Exit(0)
				}
				channel <- edges
			}
			return resp.StatusCode == 200
		}()
	}
}
Beispiel #16
0
// Ensure that a node can reply to a version check appropriately.
func TestVersionCheck(t *testing.T) {
	procAttr := new(os.ProcAttr)
	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
	args := []string{"etcd", "-n=node1", "-f", "-d=/tmp/version_check"}

	process, err := os.StartProcess(EtcdBinPath, args, procAttr)
	if err != nil {
		t.Fatal("start process failed:" + err.Error())
		return
	}
	defer process.Kill()

	time.Sleep(time.Second)

	// Check a version too small.
	resp, _ := http.Get("http://localhost:7001/version/1/check")
	resp.Body.Close()
	if resp.StatusCode != http.StatusForbidden {
		t.Fatal("Invalid version check: ", resp.StatusCode)
	}

	// Check a version too large.
	resp, _ = http.Get("http://localhost:7001/version/3/check")
	resp.Body.Close()
	if resp.StatusCode != http.StatusForbidden {
		t.Fatal("Invalid version check: ", resp.StatusCode)
	}

	// Check a version that's just right.
	resp, _ = http.Get("http://localhost:7001/version/2/check")
	resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		t.Fatal("Invalid version check: ", resp.StatusCode)
	}
}
Beispiel #17
0
// Issue 12781
func TestGetAfterClose(t *testing.T) {
	ts := NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello"))
	}))

	res, err := http.Get(ts.URL)
	if err != nil {
		t.Fatal(err)
	}
	got, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatal(err)
	}
	if string(got) != "hello" {
		t.Fatalf("got %q, want hello", string(got))
	}

	ts.Close()

	res, err = http.Get(ts.URL)
	if err == nil {
		body, _ := ioutil.ReadAll(res.Body)
		t.Fatalf("Unexected response after close: %v, %v, %s", res.Status, res.Header, body)
	}
}
Beispiel #18
0
func TestV1Metric(t *testing.T) {
	r := startV1API(getDefaultMockConfig(), "metric")
	Convey("Test Metric REST API V1", t, func() {
		Convey("Get metrics - v1/metrics", func() {
			resp, err := http.Get(
				fmt.Sprintf("http://localhost:%d/v1/metrics", r.port))
			So(err, ShouldBeNil)
			So(resp.StatusCode, ShouldEqual, 200)
			body, err := ioutil.ReadAll(resp.Body)
			So(err, ShouldBeNil)
			resp1, err := url.QueryUnescape(string(body))
			So(err, ShouldBeNil)
			So(
				fmt.Sprintf(fixtures.GET_METRICS_RESPONSE, r.port),
				ShouldResemble,
				resp1)
		})

		Convey("Get metrics from tree - v1/metrics/*namespace", func() {
			resp, err := http.Get(
				fmt.Sprintf("http://localhost:%d/v1/metrics/*namespace", r.port))
			So(err, ShouldBeNil)
			So(resp.StatusCode, ShouldEqual, 200)
			body, err := ioutil.ReadAll(resp.Body)
			So(err, ShouldBeNil)
			resp1, err := url.QueryUnescape(string(body))
			So(err, ShouldBeNil)
			So(
				fmt.Sprintf(fixtures.GET_METRICS_RESPONSE, r.port),
				ShouldResemble,
				resp1)
		})
	})
}
Beispiel #19
0
func TestResourceNotImplementedMethods(t *testing.T) {

	mux := setupMux(nil, nil)
	go func() {
		http.ListenAndServe(":8188", mux)
	}()

	resp, err := http.Get("http://localhost:8188/rest/somewire")
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	body := "{}"
	resp, err = http.Post("http://localhost:8188/rest/somewire", "text/json", strings.NewReader(body))
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	data := url.Values(map[string][]string{"nothing": []string{"bogus"}})
	resp, err = http.PostForm("http://localhost:8188/rest/somewire", data)
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	resp, err = http.Post("http://localhost:8188/rest/somewire/2", "text/json", strings.NewReader(body))
	checkHttpStatus(t, resp, err, http.StatusBadRequest)

	resp, err = http.Get("http://localhost:8188/rest/somewire/3")
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	client := new(http.Client)

	req := makeReq(t, "PUT", "http://localhost:8188/rest/somewire/4", "{}")
	resp, err = client.Do(req)
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	req = makeReq(t, "DELETE", "http://localhost:8188/rest/somewire/5", "")
	resp, err = client.Do(req)
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

}
func TestPrepareRun(t *testing.T) {
	s, etcdserver, config, assert := newMaster(t)
	defer etcdserver.Terminate(t)

	assert.NotNil(config.SwaggerConfig)
	assert.NotNil(config.OpenAPIConfig)

	server := httptest.NewServer(s.HandlerContainer.ServeMux)
	defer server.Close()

	s.PrepareRun()

	// openapi is installed in PrepareRun
	resp, err := http.Get(server.URL + "/swagger.json")
	assert.NoError(err)
	assert.Equal(http.StatusOK, resp.StatusCode)

	// swagger is installed in PrepareRun
	resp, err = http.Get(server.URL + "/swaggerapi/")
	assert.NoError(err)
	assert.Equal(http.StatusOK, resp.StatusCode)

	// healthz checks are installed in PrepareRun
	resp, err = http.Get(server.URL + "/healthz")
	assert.NoError(err)
	assert.Equal(http.StatusOK, resp.StatusCode)
	resp, err = http.Get(server.URL + "/healthz/ping")
	assert.NoError(err)
	assert.Equal(http.StatusOK, resp.StatusCode)
}
Beispiel #21
0
func TestPreserveListeners(t *testing.T) {
	var listeners int = 0
	port := getPort()
	srvMux := http.NewServeMux()
	srvMux.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
		listeners++
		res.WriteHeader(200)
		res.Write(nil)
		listeners++
	})
	server := &http.Server{
		Addr:           fmt.Sprintf(":%d", port),
		Handler:        srvMux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	Attach(server, nil)
	go server.ListenAndServe()
	sleep(1)
	var res *http.Response
	var sres *simpleResponse
	res, _ = http.Get(fmt.Sprintf("http://localhost:%d/engine.io/default/", port))
	sres = getResponse(res)
	t.Log(sres.code, sres.body)
	t.Log(listeners)
	sleep(1)
	res, _ = http.Get(fmt.Sprintf("http://localhost:%d/test", port))
	sres = getResponse(res)
	t.Log(sres.code, sres.body)
	t.Log(listeners)
}
Beispiel #22
0
func GetHostnameFromAws() {
	instanceId_url := "http://169.254.169.254/latest/meta-data/instance-id"
	res, _ := http.Get(instanceId_url)

	defer res.Body.Close()

	tmp, _ := ioutil.ReadAll(res.Body)
	instanceId := string(tmp)

	//    fmt.Println(instanceId)
	awsServerAddr := Config().AwsServerAddr
	url := awsServerAddr + instanceId
	fmt.Println(url)
	resp, _ := http.Get(url)

	defer resp.Body.Close()

	response := TagInfo{}

	decoder := json.NewDecoder(resp.Body)
	err := decoder.Decode(&response)
	if err != nil {
		log.Println("decode response from awsInfo server wrong")
	}
	Config().Hostname = response.Name + "forTesting"
}
Beispiel #23
0
func TestProxyManifestGetByTag(t *testing.T) {
	truthConfig := configuration.Configuration{
		Storage: configuration.Storage{
			"inmemory": configuration.Parameters{},
		},
	}
	truthConfig.HTTP.Headers = headerConfig

	imageName := "foo/bar"
	tag := "latest"

	truthEnv := newTestEnvWithConfig(t, &truthConfig)
	// create a repository in the truth registry
	dgst := createRepository(truthEnv, t, imageName, tag)

	proxyConfig := configuration.Configuration{
		Storage: configuration.Storage{
			"inmemory": configuration.Parameters{},
		},
		Proxy: configuration.Proxy{
			RemoteURL: truthEnv.server.URL,
		},
	}
	proxyConfig.HTTP.Headers = headerConfig

	proxyEnv := newTestEnvWithConfig(t, &proxyConfig)

	manifestDigestURL, err := proxyEnv.builder.BuildManifestURL(imageName, dgst.String())
	checkErr(t, err, "building manifest url")

	resp, err := http.Get(manifestDigestURL)
	checkErr(t, err, "fetching manifest from proxy by digest")
	defer resp.Body.Close()

	manifestTagURL, err := proxyEnv.builder.BuildManifestURL(imageName, tag)
	checkErr(t, err, "building manifest url")

	resp, err = http.Get(manifestTagURL)
	checkErr(t, err, "fetching manifest from proxy by tag")
	defer resp.Body.Close()
	checkResponse(t, "fetching manifest from proxy by tag", resp, http.StatusOK)
	checkHeaders(t, resp, http.Header{
		"Docker-Content-Digest": []string{dgst.String()},
	})

	// Create another manifest in the remote with the same image/tag pair
	newDigest := createRepository(truthEnv, t, imageName, tag)
	if dgst == newDigest {
		t.Fatalf("non-random test data")
	}

	// fetch it with the same proxy URL as before.  Ensure the updated content is at the same tag
	resp, err = http.Get(manifestTagURL)
	checkErr(t, err, "fetching manifest from proxy by tag")
	defer resp.Body.Close()
	checkResponse(t, "fetching manifest from proxy by tag", resp, http.StatusOK)
	checkHeaders(t, resp, http.Header{
		"Docker-Content-Digest": []string{newDigest.String()},
	})
}
func (t *Tools) DownloadPackageIndex(index_file, signature_file string) error {
	// Fetch the index
	resp, err := http.Get(t.IndexURL)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Read the body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	// Fetch the signature
	signature, err := http.Get(t.IndexURL + ".sig")
	if err != nil {
		return err
	}
	defer signature.Body.Close()

	// Read the body
	signature_body, err := ioutil.ReadAll(signature.Body)
	if err != nil {
		return err
	}
	ioutil.WriteFile(index_file, body, 0644)
	ioutil.WriteFile(signature_file, signature_body, 0644)

	t.LastRefresh = time.Now()

	return nil
}
Beispiel #25
0
// Create a HypeDNS name for this device
func setHypeDNS(hostname string) (response string, err error) {
	setLoc := "/_hypehost/set?hostname="
	getLoc := "/_hypehost/get"
	nodeInfoHost := "http://[fc5d:baa5:61fc:6ffd:9554:67f0:e290:7535]:8000"

	if len(hostname) == 0 {
		// The request is a "get"
		resp, err := http.Get(nodeInfoHost + getLoc)
		if err != nil {
			fmt.Println("Got an error, %s", err)
			err = fmt.Errorf("Got an error when attempting to retrieve " +
				"hostname. This is usually because you can't connect to HypeDNS. " +
				"Try again later")
			return "", err
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		fmt.Println("You are: " + string(body))
		return "", nil
	}
	// The request is a "set"
	resp, err := http.Get(nodeInfoHost + setLoc + hostname)
	if err != nil {
		fmt.Println("Got an error, %s", err)
		err = fmt.Errorf("Got an error when attempting to change hostname. " +
			"Try again later")
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println("Hostname " + string(body) + " created.")
	return "", nil
}
Beispiel #26
0
func TestSetCookie(t *testing.T) {
	ftcServer := NewServer(nil, nil)
	ts := httptest.NewServer(ftcServer)
	defer ts.Close()
	newName := "woot"
	ftcServer.cookieName = newName
	addr := ts.URL + defaultBasePath + "?transport=polling"
	resp, err := http.Get(addr)
	if err != nil {
		t.Fatalf("http get error: %v", err)
	}
	defer resp.Body.Close()
	if !strings.HasPrefix(resp.Header.Get("Set-Cookie"), newName) {
		t.Errorf("cookie not set to %s as expected. cookie set header %s", newName, resp.Header.Get("Set-Cookie"))
	}
	// The server should not set the cookie in this case.
	ftcServer.cookieName = ""
	resp, err = http.Get(addr)
	if err != nil {
		t.Fatalf("http get error: %v", err)
	}
	defer resp.Body.Close()
	if len(resp.Header.Get("Set-Cookie")) > 0 {
		t.Errorf("cookie is set to %s when it should not be", resp.Header.Get("Set-Cookie"))
	}
}
Beispiel #27
0
// Get number/date trivia from numbersapi.com (free number trivia API. Wheee!)
// Return text string for Hipchat response
func numberTrivia(query string) string {
	// Compiler barfs if we define these with `:=` in the if/else block
	var triviaResp *http.Response
	var triviaErr error

	if query == "today" {
		// Get today's date, convert month and day to int -> string, and send GET to API
		today := time.Now()
		_, month, day := today.Date()

		triviaResp, triviaErr = http.Get(NUMBERS_API_ENDPOINT + strconv.Itoa(int(month)) + "/" + strconv.Itoa(int(day)) + "/date")
	} else {
		// Straight numbers are simpler
		triviaResp, triviaErr = http.Get(NUMBERS_API_ENDPOINT + query + "/math")
	}

	// Check for error
	if triviaErr != nil {
		log.Println("Error in HTTP GET:", triviaErr)
		return "error"
	}

	// Response is text, not JSON - so we can just read it and voiala!
	byteBody, stringErr := ioutil.ReadAll(triviaResp.Body)

	if stringErr != nil {
		log.Println("Error reading response body:", stringErr)
		return "error"
	}

	return string(byteBody)
}
Beispiel #28
0
func TestConfig_buildPprof(t *testing.T) {
	a := assert.New(t)
	fh := func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte("123"))
	}

	cfg := &Config{Pprof: "/debug/"}
	h := cfg.buildPprof(http.HandlerFunc(fh))
	srv := httptest.NewServer(h)
	defer srv.Close()

	resp, err := http.Get(srv.URL + "/debug/synbol")
	a.NotError(err).NotNil(resp)
	a.Equal(resp.StatusCode, http.StatusOK)

	resp, err = http.Get(srv.URL + "/debug/cmdline")
	a.NotError(err).NotNil(resp)
	a.Equal(resp.StatusCode, http.StatusOK)

	// 不存在的路由,跳转到fh函数
	resp, err = http.Get(srv.URL + "/debug1/cmdline")
	a.NotError(err).NotNil(resp)
	a.Equal(resp.StatusCode, http.StatusNotFound)
}
Beispiel #29
0
func callbackHandler(w http.ResponseWriter, r *http.Request) {
	// Request access token
	u, _ := url.Parse(r.URL.String())
	queryParams := u.Query()
	var url string = site + "/oauth/token?client_id=" + clientID + "&client_secret=" + clientSecret + "&code=" + queryParams.Get("code") + "&grant_type=authorization_code" + "&redirect_uri=http://" + r.Host + "/cerberus-go/callback"

	resp, err := http.Get(url)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()

	bb, _ := ioutil.ReadAll(resp.Body)
	var dat map[string]interface{}
	if err := json.Unmarshal(bb, &dat); err != nil {
		panic(err)
	}
	var access_token = dat["access_token"].(string)

	// Test access token
	var api_request = userInfoApi + access_token
	resp_test, err := http.Get(api_request)
	defer resp_test.Body.Close()
	resp_test.Write(w)
}
Beispiel #30
0
func main() {
	//    id := "i-f5fe814d"
	//    name,region,_ := funcs.GetAwsInfo("id",id)

	instanceId_url := "http://169.254.169.254/latest/meta-data/instance-id"
	res, _ := http.Get(instanceId_url)
	tmp, _ := ioutil.ReadAll(res.Body)
	instanceId := string(tmp)
	//    fmt.Println(instanceId)
	url := "http://172.31.6.247:12360/v1/aws/id/" + instanceId
	//    fmt.Println(url)
	resp, _ := http.Get(url)

	type TagInfo struct {
		Name   string `json:"name"`
		Region string `json:"region"`
	}
	response := TagInfo{}

	decoder := json.NewDecoder(resp.Body)
	err := decoder.Decode(&response)
	if err != nil {
		fmt.Println("decode response from awsInfo server wrong")
	}
	fmt.Println(response.Name)
}