Golang Post示例

说明

golang post示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: benchmark_test.go 项目: qq101/influxdb

// issue #378
func (self *IntegrationSuite) TestDeletingNewDatabase(c *C) {
	resp, err := http.Post("http://localhost:8086/db?u=root&p=root", "", bytes.NewBufferString(`{"name":"delete0"}`))
	c.Assert(err, IsNil)
	defer resp.Body.Close()
	c.Assert(resp.StatusCode, Equals, http.StatusCreated)

	s := self.createPoints("data_resurrection", 1, 10)
	b, err := json.Marshal(s)
	c.Assert(err, IsNil)
	resp, err = http.Post("http://localhost:8086/db/delete0/series?u=root&p=root", "", bytes.NewBuffer(b))
	c.Assert(err, IsNil)
	c.Assert(resp.StatusCode, Equals, http.StatusOK)
	resp.Body.Close()
	time.Sleep(time.Second)
	fmt.Printf("wrote some data\n")

	for i := 0; i < 2; i++ {
		resp, err = http.Post("http://localhost:8086/db?u=root&p=root", "", bytes.NewBufferString(`{"name":"delete1"}`))
		c.Assert(err, IsNil)
		defer resp.Body.Close()
		c.Assert(resp.StatusCode, Equals, http.StatusCreated)
		req, err := http.NewRequest("DELETE", "http://localhost:8086/db/delete1?u=root&p=root", nil)
		c.Assert(err, IsNil)
		resp, err := http.DefaultClient.Do(req)
		c.Assert(err, IsNil)
		c.Assert(resp.StatusCode, Equals, http.StatusNoContent)
		resp, err = http.Get("http://localhost:8086/ping")
		c.Assert(err, IsNil)
		c.Assert(resp.StatusCode, Equals, http.StatusOK)
		resp.Body.Close()
	}
}

示例#2
文件: jenkins-server.go 项目: kesselborn/pipeline-generator

// DeletePipeline deletes all jobs and views of the named pipeline
func (js JenkinsServer) DeletePipeline(name string) (int, error) {
	l, err := js.pipelineJobs(name)
	if err != nil {
		return 0, err
	}

	buildNum, err := js.BuildNumber(name)
	if err != nil {
		return 0, err
	}

	for _, jenkinsJob := range l.Jobs {
		err := backup(jenkinsJob["name"], jenkinsJob["url"])
		if err != nil {
			return 0, err
		}

		debug("post\t%s\n", jenkinsJob["url"]+"/doDelete")
		if _, err = http.Post(jenkinsJob["url"]+"/doDelete", "application/xml", nil); err != nil {
			return 0, err
		}
	}

	err = backup("pipeline-view-"+name, string(js)+"/view/"+name+"/")
	if err != nil {
		return buildNum, err
	}

	_, err = http.Post(string(js)+"/view/"+name+"/doDelete", "application/xml", nil)

	fmt.Printf("lastbuildnum\t%d\n", buildNum)

	return buildNum, err
}

示例#3
文件: client.go 项目: hyperhq/hypernetes

// Save saves changes to a proxy such as its enabled status or upstream port.
func (proxy *Proxy) Save() error {
	request, err := json.Marshal(proxy)
	if err != nil {
		return err
	}

	var resp *http.Response
	if proxy.created {
		resp, err = http.Post(proxy.client.endpoint+"/proxies/"+proxy.Name, "text/plain", bytes.NewReader(request))
	} else {
		resp, err = http.Post(proxy.client.endpoint+"/proxies", "application/json", bytes.NewReader(request))
	}
	if err != nil {
		return err
	}

	if proxy.created {
		err = checkError(resp, http.StatusOK, "Save")
	} else {
		err = checkError(resp, http.StatusCreated, "Create")
	}
	if err != nil {
		return err
	}

	err = json.NewDecoder(resp.Body).Decode(proxy)
	if err != nil {
		return err
	}
	proxy.created = true

	return nil
}

示例#4
文件: post.go 项目: yiduoyunQ/sm

func post(b []byte, method, arg string) {
	var res *http.Response
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err.Error())
		}
	}()
	reader := bytes.NewReader(b)
	if arg == "" {
		res, err = http.Post("http://"+ip+port+"/"+method, "POST", reader)
	} else {
		res, err = http.Post("http://"+ip+port+"/"+method+"/"+arg, "POST", reader)
	}
	if err != nil {
		return
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	fmt.Println(res.Status)
	fmt.Println(string(body))
}

示例#5
文件: raft_server.go 项目: tnextday/seaweedfs

// a workaround because http POST following redirection misses request body
func postFollowingOneRedirect(target string, contentType string, b *bytes.Buffer) error {
	backupReader := bytes.NewReader(b.Bytes())
	resp, err := http.Post(target, contentType, b)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	reply, _ := ioutil.ReadAll(resp.Body)
	statusCode := resp.StatusCode

	if statusCode == http.StatusMovedPermanently {
		var urlStr string
		if urlStr = resp.Header.Get("Location"); urlStr == "" {
			return fmt.Errorf("%d response missing Location header", resp.StatusCode)
		}

		glog.V(0).Infoln("Post redirected to ", urlStr)
		resp2, err2 := http.Post(urlStr, contentType, backupReader)
		if err2 != nil {
			return err2
		}
		defer resp2.Body.Close()
		reply, _ = ioutil.ReadAll(resp2.Body)
		statusCode = resp2.StatusCode
	}

	glog.V(0).Infoln("Post returned status: ", statusCode, string(reply))
	if statusCode != http.StatusOK {
		return errors.New(string(reply))
	}

	return nil
}

示例#6
文件: single_server_test.go 项目: kennylixi/influxdb

// issue #360
func (self *SingleServerSuite) TestContinuousQueriesAfterCompaction(c *C) {
	resp, err := http.Post("http://localhost:8086/db/db1/continuous_queries?u=root&p=root", "application/json",
		bytes.NewBufferString(`{"query": "select * from foo into bar"}`))
	c.Assert(err, IsNil)
	c.Assert(resp.StatusCode, Equals, http.StatusOK)
	resp, err = http.Get("http://localhost:8086/db/db1/continuous_queries?u=root&p=root")
	c.Assert(err, IsNil)
	defer resp.Body.Close()
	c.Assert(resp.StatusCode, Equals, http.StatusOK)
	body, err := ioutil.ReadAll(resp.Body)
	c.Assert(err, IsNil)
	queries := []*h.ContinuousQuery{}
	err = json.Unmarshal(body, &queries)
	c.Assert(err, IsNil)
	c.Assert(queries, HasLen, 1)

	resp, err = http.Post("http://localhost:8086/raft/force_compaction?u=root&p=root", "", nil)
	c.Assert(err, IsNil)
	c.Assert(resp.StatusCode, Equals, http.StatusOK)

	self.server.Stop()
	c.Assert(self.server.Start(), IsNil)
	self.server.WaitForServerToStart()

	resp, err = http.Get("http://localhost:8086/db/db1/continuous_queries?u=root&p=root")
	c.Assert(err, IsNil)
	defer resp.Body.Close()
	c.Assert(resp.StatusCode, Equals, http.StatusOK)
	body, err = ioutil.ReadAll(resp.Body)
	c.Assert(err, IsNil)
	queries = []*h.ContinuousQuery{}
	err = json.Unmarshal(body, &queries)
	c.Assert(err, IsNil)
	c.Assert(queries, HasLen, 1)
}

示例#7
文件: create.go 项目: tharanga-abeyseela/terraform-datadog

func Create(d *schema.ResourceData, meta interface{}) error {
	warningBody, _ := MarshalMetric(d, "warning")
	criticalBody, _ := MarshalMetric(d, "critical")

	resW, err := http.Post(fmt.Sprintf("%s%s", MONITOR_ENDPOINT, AuthSuffix(meta)), "application/json", bytes.NewReader(warningBody))
	if err != nil {
		return fmt.Errorf("error creating warning: %s", err.Error())
	}

	resC, err := http.Post(fmt.Sprintf("%s%s", MONITOR_ENDPOINT, AuthSuffix(meta)), "application/json", bytes.NewReader(criticalBody))
	if err != nil {
		return fmt.Errorf("error creating critical: %s", err.Error())
	}

	warningMonitorID, err := GetIDFromResponse(resW)
	if err != nil {
		return err
	}
	criticalMonitorID, err := GetIDFromResponse(resC)
	if err != nil {
		return err
	}

	d.SetId(fmt.Sprintf("%s__%s", warningMonitorID, criticalMonitorID))

	return nil
}

示例#8
文件: parallel.go 项目: eloycoto/cgrates

func main() {
	log.Print("Start!")
	var wg sync.WaitGroup
	for i := 1; i < 1002; i++ {
		go func(index int) {
			wg.Add(1)
			resp, err := http.Post("http://localhost:2080/jsonrpc", "application/json", bytes.NewBuffer([]byte(fmt.Sprintf(`{"method": "ApierV1.SetAccount","params": [{"Tenant":"reglo","Account":"100%d","ActionPlanId":"PACKAGE_NEW_FOR795", "ReloadScheduler":false}], "id":%d}`, index, index))))
			if err != nil {
				log.Print("Post error: ", err)
			}
			contents, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				log.Print("Body error: ", err)
			}
			log.Printf("SetAccount(%d): %s", index, string(contents))
			wg.Done()
		}(i)
	}
	wg.Wait()
	for index := 1; index < 1002; index++ {
		resp, err := http.Post("http://localhost:2080/jsonrpc", "application/json", bytes.NewBuffer([]byte(fmt.Sprintf(`{"method": "ApierV1.GetAccountActionPlan","params": [{"Tenant":"reglo","Account":"100%d"}], "id":%d}`, index, index))))
		if err != nil {
			log.Print("Post error: ", err)
		}
		contents, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Print("Body error: ", err)
		}
		log.Printf("GetAccountActionPlan(%d): %s", index, string(contents))
	}

	log.Print("Done!")
}

示例#9
文件: http_api_test.go 项目: KSCTECHNOLOGIES/uberlog-proxy

func TestCustomPrefix(t *testing.T) {
	Convey("Given the App running with PREFIX", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		f.Prefix = "BETA"
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting a message", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__prefix\":\"BETA\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})

	Convey("Given the App running WITHOUT prefix", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting a message", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldNotContainSubstring, "\"__prefix\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})
}

示例#10
文件: raw_test.go 项目: seven5/seven5

func TestBadJson(t *testing.T) {

	mux := setupMux(nil, nil)
	go func() {
		http.ListenAndServe(":8187", mux)
	}()
	body := "{ \"Id\":1, \"Foo\":\"bar\""
	resp, err := http.Post("http://localhost:8187/rest/somewire", "text/json", strings.NewReader(body))
	checkHttpStatus(t, resp, err, http.StatusBadRequest)

	//if you try to send a really big bundle, the go level code disconnects you, so we send a bunch bunch
	//of nothing to see what happens
	x := make([]byte, 100000)
	resp, err = http.Post("http://localhost:8187/rest/somewire", "text/json", strings.NewReader(string(x)))
	checkHttpStatus(t, resp, err, http.StatusBadRequest)

	all, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("failed to read the body: %s", err)
	}
	body = string(all)
	if strings.Index(body, "too large") == -1 {
		t.Errorf("expected to get an error about data being too large but got %s", body)
	}
}

示例#11
文件: relay_test.go 项目: kronin/bosun

func TestRelay(t *testing.T) {
	schedule.DataAccess = testData
	schedule.Init(new(conf.Conf))
	rs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(204)
	}))
	defer rs.Close()
	rurl, err := url.Parse(rs.URL)
	if err != nil {
		t.Fatal(err)
	}
	ts := httptest.NewServer(Relay(rurl.Host))
	defer ts.Close()

	body := []byte(`[{
		"timestamp": 1,
		"metric": "no-gzip-works",
		"value": 123.45,
		"tags": {
			"host": "host.no.gzip",
			"other": "something"
		}
	}]`)
	if _, err := http.Post(ts.URL, "application/json", bytes.NewBuffer(body)); err != nil {
		t.Fatal(err)
	}

	bodygzip := []byte(`[{
		"timestamp": 1,
		"metric": "gzip-works",
		"value": 345,
		"tags": {
			"host": "host.gzip",
			"gzipped": "yup"
		}
	}]`)
	buf := new(bytes.Buffer)
	gw := gzip.NewWriter(buf)
	gw.Write(bodygzip)
	gw.Flush()
	if _, err := http.Post(ts.URL, "application/json", bytes.NewReader(buf.Bytes())); err != nil {
		t.Fatal(err)
	}
	time.Sleep(time.Second)

	m, _ := schedule.Search.UniqueMetrics()
	sort.Strings(m)
	if len(m) != 2 || m[0] != "gzip-works" || m[1] != "no-gzip-works" {
		t.Errorf("bad um: %v", m)
	}
	m, _ = schedule.Search.TagValuesByMetricTagKey("gzip-works", "gzipped", 0)
	if len(m) != 1 || m[0] != "yup" {
		t.Errorf("bad tvbmtk: %v", m)
	}
	m, _ = schedule.Search.TagKeysByMetric("no-gzip-works")
	sort.Strings(m)
	if len(m) != 2 || m[0] != "host" || m[1] != "other" {
		t.Errorf("bad tkbm: %v", m)
	}
}

示例#12
文件: shard_test.go 项目: plar/pachyderm

// TestChess uses our chess data set to test s3 integration.
func TestChess(t *testing.T) {
	t.Parallel()
	if testing.Short() {
		t.Skip()
	}
	// Notice this shard is behaving like 1 node of a 5000 node cluster to downsample to data.
	shard := NewShard("", "TestChessData", "TestChessPipelines", 0, 5000, etcache.NewCache())
	require.NoError(t, shard.EnsureRepos())
	s := httptest.NewServer(NewShardHTTPHandler(shard))
	defer s.Close()

	res, err := http.Post(s.URL+"/pipeline/count", "application/text", strings.NewReader(`
image ubuntu

input s3://pachyderm-data/chess

run cat /in/pachyderm-data/chess/* | wc -l > /out/count
`))
	require.NoError(t, err)
	res.Body.Close()
	res, err = http.Post(s.URL+"/commit?commit=commit1", "", nil)
	require.NoError(t, err)
	res, err = http.Get(s.URL + "/pipeline/count/file/count?commit=commit1")
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, res.StatusCode)
}

示例#13
文件: single_server_test.go 项目: vovkasm/facette

func (self *SingleServerSuite) TestLoadDatabaseConfig(c *C) {
	contents, err := ioutil.ReadFile("database_conf.json")
	c.Assert(err, IsNil)
	resp, err := http.Post("http://localhost:8086/cluster/database_configs/test_db_conf_db?u=root&p=root", "application/json", bytes.NewBuffer(contents))
	c.Assert(err, IsNil)
	c.Assert(resp.StatusCode, Equals, http.StatusCreated)

	// ensure that an invalid database conf doesn't create a db
	contents, err = ioutil.ReadFile("database_conf_invalid.json")
	c.Assert(err, IsNil)
	resp, _ = http.Post("http://localhost:8086/cluster/database_configs/bad_db?u=root&p=root", "application/json", bytes.NewBuffer(contents))
	c.Assert(resp.StatusCode, Equals, http.StatusBadRequest)

	client := self.server.GetClient("test_db_conf_db", c)
	spaces, err := client.GetShardSpaces()
	c.Assert(err, IsNil)
	c.Assert(self.getSpace("test_db_conf_db", "everything", "/.*/", spaces), NotNil)
	space := self.getSpace("test_db_conf_db", "specific", "/^something_specfic/", spaces)
	c.Assert(space, NotNil)
	c.Assert(space.Split, Equals, uint32(3))
	c.Assert(space.ReplicationFactor, Equals, uint32(2))

	series, err := client.Query("list continuous queries;")
	c.Assert(err, IsNil)
	queries := series[0].Points
	c.Assert(queries, HasLen, 2)
	c.Assert(queries[0][2], Equals, `select * from "events" into events.[id]`)
	c.Assert(queries[1][2], Equals, `select count(value) from "events" group by time(5m) into 5m.count.events`)
}

示例#14
文件: api_test.go 项目: mdevilliers/take-home

// Request: GET /<topic>/<username>
// Response codes:
// ● 200: Retrieval succeeded.
// ● 204: There are no messages available for this topic on this user.
// ● 404: The subscription does not exist.
// Response body: The body of the next message, if one exists.
func TestRetrieveFromExistingTopicReturns200(t *testing.T) {

	instance := getServerInstance()
	defer instance.Close()

	url := instance.URL + "/topic-one/user-one"

	//POST /<topic>/<username>
	http.Post(url, "text", nil)

	//POST /<topic>
	http.Post(instance.URL+"/topic-one", "text", bytes.NewBuffer([]byte("message-one")))

	//GET /<topic>/<username>
	res, _ := http.Get(url)

	content, status := parseResponse(res)

	if status != http.StatusOK {
		t.Error("Retreiving a posted message should return 200 but returned ", status)
	}

	if content != "message-one" {
		t.Error("Wrong message returned ", content)
	}

}

示例#15
文件: oauth2_token_grant_test.go 项目: phuc0302/go-oauth2

func Test_TokenGrant_validateForm_MissingClientID(t *testing.T) {
	u := new(TestUnit)
	defer u.Teardown()
	u.Setup()

	// Setup server
	controller := new(TokenGrant)
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		context := createRequestContext(r, w)
		defer recovery(context, true)

		controller.HandleForm(context, nil)
	}))
	defer ts.Close()

	response, _ := http.Post(ts.URL, "application/x-www-form-urlencoded", strings.NewReader(fmt.Sprintf("grant_type=%s", AuthorizationCodeGrant)))
	status := util.ParseStatus(response)
	if status == nil {
		t.Error(test.ExpectedNotNil)
	} else {
		if status.Code != 400 {
			t.Errorf(test.ExpectedNumberButFoundNumber, 400, status.Code)
		}
		if status.Description != fmt.Sprintf(InvalidParameter, "client_id") {
			t.Errorf(test.ExpectedInvalidParameter, "client_id", status.Description)
		}
	}

	// [Test 3] Missing client_secret
	response, _ = http.Post(ts.URL, "application/x-www-form-urlencoded", strings.NewReader(fmt.Sprintf("grant_type=%s&client_id=%s", AuthorizationCodeGrant, u.ClientID.Hex())))
	status = util.ParseStatus(response)
	if status.Description != fmt.Sprintf(InvalidParameter, "client_secret") {
		t.Errorf(test.ExpectedInvalidParameter, "client_secret", status.Description)
	}
}

示例#16
文件: req_test.go 项目: crooney/parurl

func TestResponses(t *testing.T) {
	for k, v := range urls {
		http.HandleFunc(k, BuildHandler(NewURLHandlers(v...)))
	}
	s := httptest.NewServer(http.DefaultServeMux)
	a := "http://" + s.Listener.Addr().String()
	checkBoth(a+"/baz/234/567", 200, t)
	checkGet(a+"/bar/234/567", 405, t) // no GET handler, but HEAD ok
	checkBoth(a+"/baz/", 404, t)       // no parameterized part
	checkBoth(a+"/dsghsdfg/", 404, t)  // bad url

	r, err := http.Post(a+"/foo/4536345", "image/jpeg", nil)
	if err != nil {
		t.Errorf("%v for %v", err, "foo post")
	}
	if r.StatusCode != 405 {
		t.Errorf("foo post status should be 405 but is %u", r.StatusCode)
	}

	r, err = http.Post(a+"/baz/4536345", "image/jpeg", nil)
	if err != nil {
		t.Errorf("%v for %v", err, "foo post")
	}
	if r.StatusCode != 200 {
		t.Errorf("baz post status should be 200 but is %u", r.StatusCode)
	}
	//should do PUT and DELETE but PITA.  They work.

}

示例#17
文件: raw_test.go 项目: seven5/seven5

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)

}

示例#18
文件: single_server_test.go 项目: richthegeek/influxdb

// issue #342, #371
func (self *SingleServerSuite) TestDataResurrectionAfterRestart(c *C) {
	s := CreatePoints("data_resurrection", 1, 10)
	self.server.WriteData(s, c)
	self.server.WaitForServerToSync()
	fmt.Printf("wrote some data\n")
	series := self.server.RunQuery("select count(column0) from data_resurrection", "s", c)
	c.Assert(series, HasLen, 1)
	c.Assert(series[0].Points[0][1], Equals, 10.0)
	req, err := http.NewRequest("DELETE", "http://localhost:8086/db/db1?u=root&p=root", nil)
	c.Assert(err, IsNil)
	resp, err := http.DefaultClient.Do(req)
	c.Assert(err, IsNil)
	c.Assert(resp.StatusCode, Equals, http.StatusNoContent)
	resp, err = http.Post("http://localhost:8086/db?u=root&p=root", "", bytes.NewBufferString("{\"name\":\"db1\", \"replicationFactor\":3}"))
	c.Assert(err, IsNil)
	defer resp.Body.Close()
	c.Assert(resp.StatusCode, Equals, http.StatusCreated)
	resp, err = http.Post("http://localhost:8086/db/db1/users?u=root&p=root", "", bytes.NewBufferString("{\"name\":\"user\", \"password\":\"pass\"}"))
	c.Assert(err, IsNil)
	defer resp.Body.Close()
	c.Assert(resp.StatusCode, Equals, http.StatusOK)
	self.server.Stop()
	c.Assert(self.server.Start(), IsNil)
	self.server.WaitForServerToStart()
	series = self.server.RunQuery("select count(column0) from data_resurrection", "s", c)
	c.Assert(series, HasLen, 0)
	series = self.server.RunQuery("list series", "s", c)
	c.Assert(series, HasLen, 0)
}

示例#19
文件: main.go 项目: mitre/ptmatch

// This application will create a new record set in the patient matching test
// harness. This record set will be associated with a FHIR resource tag.
// It will go through a directory of patient resources, in JSON format, read
// them in, apply the tag, and then upload them to the FHIR server.
func main() {
	fhirURL := flag.String("fhirURL", "", "URL for the patient matching test harness server")
	recordSetName := flag.String("name", "", "Name of the record set")
	path := flag.String("path", "", "Path to the JSON files")

	flag.Parse()

	argsToName := map[string]string{"fhirURL": *fhirURL, "name": *recordSetName, "path": *path}
	for argName, argValue := range argsToName {
		if argValue == "" {
			fmt.Printf("You must provide an argument for %s\n", argName)
			return
		}
	}

	trimmedFhirURL := strings.TrimRight(*fhirURL, "/")

	recordSet := &ptm_models.RecordSet{Name: *recordSetName}

	recordSet.ResourceType = "Patient"
	recordSet.Parameters = generateRecordSetParameters(trimmedFhirURL, *recordSetName)
	rsj, _ := json.Marshal(recordSet)
	body := bytes.NewReader(rsj)

	recordSetURL := trimmedFhirURL + "/RecordSet"
	http.Post(recordSetURL, "application/json", body)

	files, err := ioutil.ReadDir(*path)
	if err != nil {
		fmt.Printf("Couldn't read the directory: %s\n", err.Error())
		return
	}
	for _, file := range files {
		if strings.HasSuffix(file.Name(), ".json") {
			jsonBlob, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", *path, file.Name()))
			patient := &fhir_models.Patient{}
			if err != nil {
				fmt.Printf("Couldn't read the JSON file: %s\n", err.Error())
				return
			}
			json.Unmarshal(jsonBlob, patient)
			tagCoding := fhir_models.Coding{System: tagURL, Code: tagValue(*recordSetName)}
			meta := &fhir_models.Meta{Tag: []fhir_models.Coding{tagCoding}}
			patient.Meta = meta
			pj, _ := json.Marshal(patient)
			pb := bytes.NewReader(pj)
			patientURL := trimmedFhirURL + "/Patient"
			resp, err := http.Post(patientURL, "application/json", pb)
			if err != nil {
				fmt.Printf("Couldn't upload patient: %s\n", err.Error())
				return
			}
			if resp.StatusCode != http.StatusCreated {
				fmt.Sprintf("Unexpected status code when creating a patient: %d\n", resp.StatusCode)
				return
			}
		}
	}
}

示例#20
文件: client.go 项目: lamproae/gohttptun

func main() {
	flag.Parse()
	log.SetPrefix("httptun.c: ")

	listener, err := net.Listen("tcp", *listenAddr)
	if err != nil {
		panic(err)
	}
	log.Println("listen", *listenAddr)

	conn, err := listener.Accept()
	if err != nil {
		panic(err)
	}
	log.Println("accept conn", "localAddr.", conn.LocalAddr(), "remoteAddr.", conn.RemoteAddr())

	buf := new(bytes.Buffer)

	// initiate new session and read key
	log.Println("Attempting connect HttpTun Server.", *httpAddr, "for dest.", *destAddr)
	buf.Write([]byte(*destAddr))
	resp, err := http.Post(
		"http://"+*httpAddr+"/create",
		"text/plain",
		buf)
	if err != nil {
		panic(err)
	}
	key, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	log.Println("ResponseWriterected, key", key)

	// ticker to set a rate at which to hit the server
	tick := time.NewTicker(time.Duration(int64(*tickInterval)) * time.Millisecond)
	read := makeReadChan(conn, bufSize)
	buf.Reset()
	for {
		select {
		case <-tick.C:
			// write buf to new http request
			req := bytes.NewBuffer(key)
			buf.WriteTo(req)
			resp, err := http.Post(
				"http://"+*httpAddr+"/ping",
				"application/octet-stream",
				req)
			if err != nil {
				log.Println(err.Error())
				continue
			}
			// write http response response to conn
			io.Copy(conn, resp.Body)
			resp.Body.Close()
		case b := <-read:
			buf.Write(b)
		}
	}
}

示例#21
文件: user.go 项目: hahadsg/GoOnlineJudge

func (this *UserController) Detail(w http.ResponseWriter, r *http.Request) {
	log.Println("User Detail")
	this.Init(w, r)

	args := this.ParseURL(r.URL.Path)
	uid := args["uid"]
	response, err := http.Post(config.PostHost+"/user/detail/uid/"+uid, "application/json", nil)
	defer response.Body.Close()
	if err != nil {
		http.Error(w, "post error", 500)
		return
	}

	var one user
	if response.StatusCode == 200 {
		err = this.LoadJson(response.Body, &one)
		if err != nil {
			http.Error(w, "load error", 400)
			return
		}
		this.Data["Detail"] = one
	}

	response, err = http.Post(config.PostHost+"/solution/achieve/uid/"+uid, "application/json", nil)
	defer response.Body.Close()
	if err != nil {
		http.Error(w, "post error", 500)
		return
	}

	solvedList := make(map[string][]int)
	if response.StatusCode == 200 {
		err = this.LoadJson(response.Body, &solvedList)
		if err != nil {
			http.Error(w, "load error", 400)
			return
		}
		this.Data["List"] = solvedList["list"]
	}

	t := template.New("layout.tpl")
	t, err = t.ParseFiles("view/layout.tpl", "view/user_detail.tpl")
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	this.Data["Title"] = "User Detail"
	if uid != "" && uid == this.Uid {
		this.Data["IsSettings"] = true
		this.Data["IsSettingsDetail"] = true
	}

	err = t.Execute(w, this.Data)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
}

示例#22
文件: service_test.go 项目: Metasemi/susen.go

func TestAssignHandlerErrors(t *testing.T) {
	p, err := New(append([]int{SudokuGeometryCode}, rotation4Puzzle1PartialValues...))
	if err != nil {
		t.Fatalf("Failed to create initial puzzle: %v", err)
	}

	handler := func(w http.ResponseWriter, r *http.Request) {
		_, err := AssignHandler(p, w, r)
		if err == nil {
			t.Errorf("Successful assignment!")
		}
		t.Logf("Server err: %v", err)
	}
	ts := httptest.NewServer(http.HandlerFunc(handler))
	defer ts.Close()

	bytes, err := json.Marshal([]int{1, 2, 3})
	if err != nil {
		t.Fatalf("Failed to encode []int{1, 2, 3}: %v", err)
	}
	t.Logf("%s\n", bytes)
	r, e := http.Post(ts.URL, "application/json", strings.NewReader(string(bytes)))
	if e != nil {
		t.Fatalf("Request error: %v", e)
	}
	t.Logf("%q\n", r.Status)
	t.Logf("%v\n", r.Header)
	if r.StatusCode != http.StatusBadRequest {
		t.Errorf("Status was %v, expected %v", r.StatusCode, http.StatusBadRequest)
	}
	b, e := ioutil.ReadAll(r.Body)
	r.Body.Close()
	if e != nil {
		t.Fatalf("Read error on result: %v", e)
	}
	t.Logf("%s\n", b)

	bytes, err = json.Marshal(Choice{14, 2})
	if err != nil {
		t.Fatalf("Failed to encode Choice{14, 2}: %v", err)
	}
	t.Logf("%s\n", bytes)
	r, e = http.Post(ts.URL, "application/json", strings.NewReader(string(bytes)))
	if e != nil {
		t.Fatalf("Request error: %v", e)
	}
	t.Logf("%q\n", r.Status)
	t.Logf("%v\n", r.Header)
	if r.StatusCode != http.StatusBadRequest {
		t.Errorf("Status was %v, expected %v", r.StatusCode, http.StatusBadRequest)
	}
	b, e = ioutil.ReadAll(r.Body)
	r.Body.Close()
	if e != nil {
		t.Fatalf("Read error on result: %v", e)
	}
	t.Logf("%s\n", b)
}

示例#23
文件: request_bin_test.go 项目: parasnarang/requestBin-1

func TestMaximumRequestCount(t *testing.T) {
	reqs := NewRequestBin(MockServerConfig{MaximumRequestCount: 2}).CaptureRequests(func(url string) {
		http.Post(url, "text/plain", strings.NewReader("Hello"))
		http.Post(url, "text/plain", strings.NewReader("Hello"))
		http.Post(url, "text/plain", strings.NewReader("Hello"))
	})

	assert.Equal(t, 2, len(reqs))
}

示例#24
文件: shard_test.go 项目: plar/pachyderm

func TestWordCount(t *testing.T) {
	t.Parallel()
	cache := etcache.NewTestCache()
	// Setup 2 shards
	shard1 := NewShard("", "TestWordCountData-0-2", "TestWordCountPipelines-0-2", 0, 2, cache)
	require.NoError(t, shard1.EnsureRepos())
	s1 := httptest.NewServer(NewShardHTTPHandler(shard1))
	defer s1.Close()
	shard2 := NewShard("", "TestWordCountData-1-2", "TestWordCountPipelines-1-2", 1, 2, cache)
	require.NoError(t, shard2.EnsureRepos())
	s2 := httptest.NewServer(NewShardHTTPHandler(shard2))
	defer s2.Close()

	checkWriteFile(t, s1.URL, path.Join("data", "1"), "master",
		`Mr and Mrs Dursley, of number four, Privet Drive, were proud to say that they
were perfectly normal, thank you very much. They were the last people you'd
expect to be involved in anything strange or mysterious, because they just
didn't hold with such nonsense.`)
	checkWriteFile(t, s2.URL, path.Join("data", "2"), "master",
		`Mr Dursley was the director of a firm called Grunnings, which made drills.
He was a big, beefy man with hardly any neck, although he did have a very
large moustache. Mrs Dursley was thin and blonde and had nearly twice the
usual amount of neck, which came in very useful as she spent so much of her
time craning over garden fences, spying on the neighbours. The Dursleys had
a small son called Dudley and in their opinion there was no finer boy
anywhere.`)

	// Spoof the shards in etcache
	cache.SpoofMany("/pfs/master", []string{s1.URL, s2.URL}, false)

	pipeline := `
image ubuntu

input data

run mkdir /out/counts
run cat /in/data/* | tr -cs "A-Za-z'" "\n" | sort | uniq -c | sort -n -r | while read count; do echo ${count% *} >/out/counts/${count#* }; done
shuffle counts
run find /out/counts | while read count; do cat $count | awk '{ sum+=$1} END {print sum}' >/tmp/count; mv /tmp/count $count; done
`
	res, err := http.Post(s1.URL+"/pipeline/wc", "application/text", strings.NewReader(pipeline))
	require.NoError(t, err)
	res.Body.Close()
	res, err = http.Post(s2.URL+"/pipeline/wc", "application/text", strings.NewReader(pipeline))
	require.NoError(t, err)
	res.Body.Close()

	res, err = http.Post(s1.URL+"/commit?commit=commit1", "", nil)
	require.NoError(t, err)
	res.Body.Close()
	res, err = http.Post(s2.URL+"/commit?commit=commit1", "", nil)
	require.NoError(t, err)
	res.Body.Close()

	// There should be 3 occurances of Dursley
	checkFile(t, s1.URL+"/pipeline/wc", path.Join("counts", "Dursley"), "commit1", "3\n")
}

示例#25
文件: shard_test.go 项目: plar/pachyderm

func TestShuffle(t *testing.T) {
	t.Parallel()
	cache := etcache.NewTestCache()
	// Setup 2 shards
	shard1 := NewShard("", "TestShuffleData-0-2", "TestShufflePipelines-0-2", 0, 2, cache)
	require.NoError(t, shard1.EnsureRepos())
	s1 := httptest.NewServer(NewShardHTTPHandler(shard1))
	defer s1.Close()
	shard2 := NewShard("", "TestShuffleData-1-2", "TestShufflePipelines-1-2", 1, 2, cache)
	require.NoError(t, shard2.EnsureRepos())
	s2 := httptest.NewServer(NewShardHTTPHandler(shard2))
	defer s2.Close()

	files := []string{"foo", "bar", "fizz", "buzz"}

	for _, file := range files {
		checkWriteFile(t, s1.URL, path.Join("data", file), "master", file)
		checkWriteFile(t, s2.URL, path.Join("data", file), "master", file)
	}

	// Spoof the shards in etcache
	cache.SpoofMany("/pfs/master", []string{s1.URL, s2.URL}, false)

	pipeline := `
image ubuntu

input data

run cp -r /in/data /out

shuffle data
`
	res, err := http.Post(s1.URL+"/pipeline/shuffle", "application/text", strings.NewReader(pipeline))
	require.NoError(t, err)
	res.Body.Close()
	res, err = http.Post(s2.URL+"/pipeline/shuffle", "application/text", strings.NewReader(pipeline))
	require.NoError(t, err)
	res.Body.Close()

	res, err = http.Post(s1.URL+"/commit?commit=commit1", "", nil)
	require.NoError(t, err)
	res, err = http.Post(s2.URL+"/commit?commit=commit1", "", nil)
	require.NoError(t, err)

	for _, file := range files {
		match, err := route.Match(path.Join("data", file), "0-2")
		require.NoError(t, err)
		if match {
			log.Print("shard: s1 file: ", file)
			checkFile(t, s1.URL+"/pipeline/shuffle", path.Join("data", file), "commit1", file+file)
		} else {
			log.Print("shard: s2 file: ", file)
			checkFile(t, s2.URL+"/pipeline/shuffle", path.Join("data", file), "commit1", file+file)
		}
	}
}

示例#26
文件: app_volume_test.go 项目: pkoro/heketi

func TestVolumeCreateBadDispersionValues(t *testing.T) {
	tmpfile := tests.Tempfile()
	defer os.Remove(tmpfile)

	// Create the app
	app := NewTestApp(tmpfile)
	defer app.Close()
	router := mux.NewRouter()
	app.SetRoutes(router)

	// Setup the server
	ts := httptest.NewServer(router)
	defer ts.Close()

	// VolumeCreate JSON Request
	request := []byte(`{
        "size" : 100,
        "durability": {
        	"type": "disperse",
        	"disperse": {
            	"data" : 8,
            	"redundancy" : 1
        	}
    	}
    }`)

	// Send request
	r, err := http.Post(ts.URL+"/volumes", "application/json", bytes.NewBuffer(request))
	tests.Assert(t, err == nil)
	tests.Assert(t, r.StatusCode == http.StatusBadRequest)
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, r.ContentLength))
	tests.Assert(t, err == nil)
	r.Body.Close()
	tests.Assert(t, strings.Contains(string(body), "Invalid dispersion combination"))

	// VolumeCreate JSON Request
	request = []byte(`{
        "size" : 100,
        "durability": {
        	"type": "disperse",
        	"disperse": {
            	"data" : 4,
            	"redundancy" : 3
        	}
    	}
    }`)

	// Send request
	r, err = http.Post(ts.URL+"/volumes", "application/json", bytes.NewBuffer(request))
	tests.Assert(t, err == nil)
	tests.Assert(t, r.StatusCode == http.StatusBadRequest)
	body, err = ioutil.ReadAll(io.LimitReader(r.Body, r.ContentLength))
	tests.Assert(t, err == nil)
	r.Body.Close()
	tests.Assert(t, strings.Contains(string(body), "Invalid dispersion combination"))
}

示例#27
文件: meetup.go 项目: istanbul-coders/monsterghost

func createEvent(apikey string, gid string, name string, desc string, vid string, rsvp_limit string, epocs string) *meetup.Event {
	meetup_url := "https://api.meetup.com/2/event/"
	meetup_root_url := meetup_url

	key := fmt.Sprintf("?key=%s", apikey)
	meetup_url = fmt.Sprint(meetup_url, key)

	groupUrlName := "&group_urlname=Istanbul-Hackers"
	meetup_url = fmt.Sprint(meetup_url, groupUrlName)

	groupId := fmt.Sprintf("&group_id=%s", gid)
	meetup_url = fmt.Sprint(meetup_url, groupId)

	venue := fmt.Sprintf("&venue_id=%s", vid)
	meetup_url = fmt.Sprint(meetup_url, venue)

	rsvp_limit = fmt.Sprintf("&rsvp_limit=%s", rsvp_limit)
	meetup_url = fmt.Sprint(meetup_url, rsvp_limit)

	epocs_in_ms, _ := time.Parse(time.RFC1123Z, epocs)
	epocs_txt := fmt.Sprintf("&time=%d", (epocs_in_ms.UnixNano() / int64(time.Millisecond)))
	fmt.Println("Epocs in txt: ", epocs_txt)
	meetup_url = fmt.Sprint(meetup_url, epocs_txt)

	name = fmt.Sprintf("&name=%s", url.QueryEscape(name))
	meetup_url = fmt.Sprint(meetup_url, name)

	description := fmt.Sprintf("&description=%s", url.QueryEscape(desc))
	meetup_url = fmt.Sprint(meetup_url, description)

	fmt.Println("Url :", meetup_url)
	resp, err := http.Post(meetup_url, "application/x-www-form-urlencoded", nil)
	if err != nil {
		fmt.Println("Error occured while creating meetup event", err)
		os.Exit(1)
	}
	fmt.Println("Post Response:", resp)
	event := new(meetup.Event)
	decoder := json.NewDecoder(resp.Body)
	decoder.Decode(event)
	fmt.Println(event)

	meetup_root_url = meetup_root_url + event.Id
	meetup_root_url = fmt.Sprint(meetup_root_url, key)
	meetup_root_url = meetup_root_url + "&announce=true"

	fmt.Println("Meetup update request url:", meetup_root_url)
	resp, err = http.Post(meetup_root_url, "application/x-www-form-urlencoded", nil)
	if err != nil {
		fmt.Println("Error occured while announcing meetup event", err)

		os.Exit(1)
	}
	fmt.Println("Post Response:", resp)
	return event
}

示例#28
文件: app_device_test.go 项目: Zandrr/heketi

func TestDeviceAddBadRequests(t *testing.T) {
	tmpfile := tests.Tempfile()
	defer os.Remove(tmpfile)

	// Patch dbfilename so that it is restored at the end of the tests
	defer tests.Patch(&dbfilename, tmpfile).Restore()

	// Create the app
	app := NewApp()
	defer app.Close()
	router := mux.NewRouter()
	app.SetRoutes(router)

	// Setup the server
	ts := httptest.NewServer(router)
	defer ts.Close()

	// ClusterCreate JSON Request
	request := []byte(`{
        bad json
    }`)

	// Post bad JSON
	r, err := http.Post(ts.URL+"/devices", "application/json", bytes.NewBuffer(request))
	tests.Assert(t, err == nil)
	tests.Assert(t, r.StatusCode == 422)

	// Make a request with no devices
	request = []byte(`{
        "node" : "123",
        "devices" : []
    }`)

	// Post bad JSON
	r, err = http.Post(ts.URL+"/devices", "application/json", bytes.NewBuffer(request))
	tests.Assert(t, err == nil)
	tests.Assert(t, r.StatusCode == http.StatusBadRequest)

	// Make a request with unknown node
	request = []byte(`{
        "node" : "123",
        "devices" : [
            {
                "name" : "/dev/fake",
                "weight" : 20
            }
        ]
    }`)

	// Post bad JSON
	r, err = http.Post(ts.URL+"/devices", "application/json", bytes.NewBuffer(request))
	tests.Assert(t, err == nil)
	tests.Assert(t, r.StatusCode == http.StatusNotFound)

}

示例#29
文件: request_bin_test.go 项目: parasnarang/requestBin-1

func TestGlobalTimeout(t *testing.T) {
	reqs := NewRequestBin(MockServerConfig{GlobalTimeout: 1}).CaptureRequests(func(url string) {
		http.Post(url, "text/plain", strings.NewReader("Hello"))
		go func() {
			<-time.After(time.Second * 3)
			http.Post(url, "text/plain", strings.NewReader("It's me"))
		}()
	})

	assert.Equal(t, 1, len(reqs))
}

示例#30
文件: main_test.go 项目: jeisc/sneakynote.com

func TestPostNoteDuplicateUuid(t *testing.T) {
	testServer := httptest.NewServer(main.Handlers())
	defer testServer.Close()
	main.SetupStore()
	defer main.TeardownStore()

	reqBodyReader := strings.NewReader("this is my secret")
	response, err := http.Post(testServer.URL+"/notes/fc2a4122-e81e-4b10-a31b-d79fbdb33a27", "application/octet-stream", reqBodyReader)

	reqBodyReader = strings.NewReader("this is my secret")
	response, err = http.Post(testServer.URL+"/notes/fc2a4122-e81e-4b10-a31b-d79fbdb33a27", "application/octet-stream", reqBodyReader)

	if err != nil {
		t.Error(err)
		return
	}

	if response.StatusCode != 403 {
		t.Errorf("Expected status 403, got %d", response.StatusCode)
	}

	if response.Header.Get("Content-Type") != "application/json" {
		t.Errorf("Expected \"Content-Type: application-json\", got %s", response.Header.Get("Content-Type"))
	}

	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)

	if !strings.Contains(string(body), "\"error_type\": \"duplicate_id\"") {
		t.Errorf("Expected to find \"\"error_type\": \"duplicate_id\"\" in %s", body)
	}

	if !strings.Contains(string(body), "\"error_message\": \"A secret with that ID has already been created. If you are not an attacker trying to replace the secret, this indicates a bug in your program and a potentially insecure source of randomness. As a precaution/penalty, the secret has been destroyed (if it has not already expired or been accessed).\"") {
		t.Errorf("Expected to find \"\"error_message\": \"A secret with that ID has already been created. If you are not an attacker trying to replace the secret, this indicates a bug in your program and a potentially insecure source of randomness. As a precaution/penalty, the secret has been destroyed (if it has not already expired or been accessed).\"\" in %s", body)
	}

	defer response.Body.Close()
	response, err = http.Get(testServer.URL + "/notes/fc2a4122-e81e-4b10-a31b-d79fbdb33a27")

	if err != nil {
		t.Error(err)
		return
	}

	if response.StatusCode != 403 {
		t.Errorf("Expected status 403, got %d", response.StatusCode)
	}

	body, _ = ioutil.ReadAll(response.Body)

	if !bytes.Equal(body, []byte("")) {
		t.Errorf("Expected returned data to be blank, got %s", string(body))
	}
}

展开阅读全文