本文整理汇总了Golang中net/http.Post函数的典型用法代码示例。如果您正苦于以下问题:Golang Post函数的具体用法?Golang Post怎么用?Golang Post使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Post函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestDeletingNewDatabase
// 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: DeletePipeline
// 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: Save
// 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
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: postFollowingOneRedirect
// 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: TestContinuousQueriesAfterCompaction
// 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
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: main
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: TestCustomPrefix
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: TestBadJson
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: TestRelay
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: TestChess
// 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: TestLoadDatabaseConfig
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: TestRetrieveFromExistingTopicReturns200
// 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: Test_TokenGrant_validateForm_MissingClientID
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)
}
}