//LogRequestFromValidationResult unmarshalls the ValidationResult and logs to keen.io // //http://api.keen.io/3.0/projects/<project_id>/events/<event_collection> func (keen *KeenMetrics) LogRequestFromValidationResult(collectionName string, validationResult string) { var url = keen.getEndpoint() + collectionName var result goiban.ValidationResult json.Unmarshal([]byte(validationResult), &result) req := goreq.Request{ Method: "POST", Uri: url, ContentType: "application/json", Body: ValidationResultToEvent(&result), } req.AddHeader("Authorization", keen.WriteAPIKey) res, err := req.Do() if err != nil { log.Printf("Error while posting stats: %v", err) return } // Close the response body if res.Body != nil { defer res.Body.Close() } if collectionName == "Test" { log.Printf(url) text, _ := res.Body.ToString() log.Printf("Response (%v): %v", res.StatusCode, text) } }
func (m webhooksAlerter) Worker(q chan webhook) { for { select { case webhook := <-q: log.Info("Sending webhook alert to %s", webhook.Url) req := goreq.Request{ Uri: webhook.Url, Accept: "application/json", ContentType: "application/json", UserAgent: "Lovebeat", Timeout: 10 * time.Second, Body: webhook.Data, } req.AddHeader("X-Lovebeat", "1") _, err := req.Do() if err != nil { log.Error("Failed to post webhook: %s", err) } } } }
func (c Client) post(url string, requestData interface{}) []error { var errs []error req := goreq.Request{ Method: "POST", Body: requestData, Uri: url, ContentType: "application/x-www-form-urlencoded; charset=UTF-8", CookieJar: c.cookie, } req.AddHeader("X-Requested-With", "XMLHttpRequest") resp, err := req.Do() if err != nil { errs = append(errs, errors.New(err.Error())) log.Fatalln(err.Error()) } defer func() { err := resp.Body.Close() if err != nil { log.Fatal(err) } }() if resp.StatusCode != http.StatusOK { errs = append(errs, errors.New("Failed login: status code is "+resp.Status)) } return errs }
// sendRequest is an internal method to send the prepared requests to OpsGenie. func (cli *OpsGenieClient) sendRequest(req goreq.Request) (*goreq.Response, error) { // send the request var resp *goreq.Response var err error for i := 0; i < cli.httpTransportSettings.MaxRetryAttempts; i++ { resp, err = req.Do() if err == nil && resp.StatusCode < 500 { break } if resp != nil { defer resp.Body.Close() logging.Logger().Info(fmt.Sprintf("Retrying request [%s] ResponseCode:[%d]. RetryCount: %d", req.Uri, resp.StatusCode, (i + 1))) } else { logging.Logger().Info(fmt.Sprintf("Retrying request [%s] Reason:[%s]. RetryCount: %d", req.Uri, err.Error(), (i + 1))) } time.Sleep(timeSleepBetweenRequests * time.Duration(i+1)) } if err != nil { message := "Unable to send the request " + err.Error() logging.Logger().Warn(message) return nil, errors.New(message) } // check for the returning http status statusCode := resp.StatusCode if statusCode >= 400 { body, err := resp.Body.ToString() if err != nil { message := "Server response with error can not be parsed " + err.Error() logging.Logger().Warn(message) return nil, errors.New(message) } return nil, errorMessage(statusCode, body) } return resp, nil }
func (wa *webAuth) callURL(url, method string, body interface{}, statusCode int, resJSON interface{}) (res *goreq.Response, err error) { req := goreq.Request{ Method: method, Uri: url, Body: body, CookieJar: wa.jar, Accept: "application/json", Host: "hub.docker.com", ContentType: "application/json", }.WithHeader("Referer", "https://hub.docker.com/login/") if wa.token != "" { req = req.WithHeader("Authorization", fmt.Sprintf("JWT %v", wa.token)) } res, err = req.Do() if err != nil { return res, wrapError(err, fmt.Sprintf("%v to %v", method, url)) } if statusCode != 0 && res.StatusCode != statusCode { return res, wrongResponseError(res, fmt.Sprintf("%v to %v should have returned a %v", method, url, statusCode)) } if resJSON == nil { return } err = res.Body.FromJsonTo(resJSON) if err != nil { return res, wrapError(err, fmt.Sprintf("extracting JSON from %v to %v", method, url)) } return }
// 获取预授权码,用于公众号oauth func (ra *regularApi) GetPreAuthCode(accessToken string) (string, float64) { postData := struct { Component_appid string `json:"component_appid"` }{ Component_appid: ra.wt.appId, } res, err := goreq.Request{ Method: "POST", Uri: fmt.Sprintf(apiCreatePreAuthCode, accessToken), Body: postData, }.Do() if err != nil { log.Println("getPreAuthCode api failed: ", err.Error()) return "", 0 } result := &struct { PAC string `json:"pre_auth_code"` ExpiresIn float64 `json:"expires_in"` }{} err = unmarshalResponseToJson(res, result) if err != nil { log.Println("Parse pre auth token failed: ", err) return "", 0 } return result.PAC, result.ExpiresIn }
// 获取第三方平台令牌 func (ra *regularApi) GetAccessToken(ticket string) (string, float64) { postData := struct { Component_appid string `json:"component_appid"` Component_appsecret string `json:"component_appsecret"` Component_verify_ticket string `json:"component_verify_ticket"` }{ Component_appid: ra.wt.appId, Component_appsecret: ra.wt.appSecret, Component_verify_ticket: ticket, } res, err := goreq.Request{ Method: "POST", Uri: apiComponentToken, Body: postData, }.Do() if err != nil { log.Println("getAccessToken api failed: ", err.Error()) return "", 0 } result := &struct { CAT string `json:"component_access_token"` ExpiresIn float64 `json:"expires_in"` }{} err = unmarshalResponseToJson(res, result) if err != nil { log.Println("Parse access token failed: ", err) } return result.CAT, result.ExpiresIn }
//retrieve object from the object store func (u *UserGraphResource) getObject(id string, response *restful.Response) (*Object, error) { res, err := goreq.Request{ Uri: u.baseUrl + id, Accept: "application/json", ContentType: "application/json", }.Do() if err != nil { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) return nil, errors.New("500") } if res.StatusCode == 404 { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusNotFound, "Requested item could not be found.") return nil, errors.New("404") } if res.StatusCode != 200 { response.AddHeader("Content-Type", "text/plain") value, _ := res.Body.ToString() response.WriteErrorString(http.StatusInternalServerError, "Object store returned: "+ strconv.Itoa(res.StatusCode)+" Response body:\n"+value) return nil, errors.New(strconv.Itoa(res.StatusCode)) } obj := new(Object) res.Body.FromJsonTo(&obj) res.Body.Close() return obj, nil }
//WriteLogRequest logs to keen.io // // http://api.keen.io/3.0/projects/<project_id>/events/<event_collection> func (keen *KeenMetrics) WriteLogRequest(collectionName string, iban *goiban.Iban) { var url = keen.getEndpoint() + collectionName req := goreq.Request{ Method: "POST", Uri: url, ContentType: "application/json", Body: IbanToEvent(iban), } req.AddHeader("Authorization", keen.WriteAPIKey) res, err := req.Do() if err != nil { log.Printf("Error while posting stats: %v", err) return } // Close the response body if res.Body != nil { defer res.Body.Close() } if collectionName == "Test" { log.Printf(url) text, _ := res.Body.ToString() log.Printf("Response (%v): %v", res.StatusCode, text) } }
func Dispatch(req goreq.Request) (string, error) { // --debug to show only request uri (plus data if POSTing) for _, arg := range os.Args { if arg == "-d" || arg == "--debug" { httpreq, _ := req.NewRequest() fmt.Printf("%# v", pretty.Formatter(httpreq)) os.Exit(0) } } // dispatch res, err := req.Do() if err != nil { fmt.Println(err.Error()) os.Exit(1) } body, err := res.Body.ToString() // --prettify for _, arg := range os.Args { if arg == "--prettify" { body, _ = PrettifyJson(body) } } return body, err }
func (m slackhookAlerter) Worker(q chan slackhook, cfg *config.ConfigSlackhook) { for { select { case slackhook := <-q: var err error var context = make(map[string]interface{}) context["View"] = slackhook.Data.View context["Previous"] = slackhook.Data.Previous context["Current"] = slackhook.Data.Current var doc bytes.Buffer err = m.template.Execute(&doc, context) if err != nil { log.Error("Failed to render template", err) return } req := goreq.Request{ Method: "POST", Uri: cfg.Uri, Accept: "*/*", ContentType: "application/x-www-form-urlencoded", UserAgent: "Lovebeat", Timeout: 10 * time.Second, Body: "payload=" + url.QueryEscape(doc.String()), } req.AddHeader("X-Lovebeat", "1") res, err := req.Do() if err != nil { log.Error("Failed to post slackhook:%v:", err) } robots, err := ioutil.ReadAll(res.Body) res.Body.Close() //it returned a 200 so ignore any error here if err != nil { log.Error("OK:unreadable response:%v:", err) } else if res.StatusCode != http.StatusOK { log.Error("NOK:non-200:%d:", res.StatusCode) } else { log.Info("OK:response:%s:", string(robots)) } } } }
func (c Client) get(url string, requestData interface{}, result interface{}) []error { var errs []error resp, err := goreq.Request{ Uri: url, QueryString: requestData, CookieJar: c.cookie, }.Do() if err != nil { errs = append(errs, errors.New(err.Error())) log.Fatalln(err.Error()) } defer func() { err := resp.Body.Close() if err != nil { log.Fatal(err) } }() if resp.StatusCode != http.StatusOK { errs = append(errs, errors.New("Failed login: status code is "+resp.Status)) } err = resp.Body.FromJsonTo(&result) if err != nil { errs = append(errs, errors.New(err.Error())) log.Println(err.Error()) } return errs }
func serveValidateServerAuth(backend backend, w http.ResponseWriter, req *http.Request) bool { info := backend.GetInfo() serverAuth := info.ServerAuth if serverAuth == nil { return false } if !strings.HasSuffix(req.URL.Path, SERVER_AUTH_ENDPOINT) { return false } originalPath := strings.Replace(req.URL.Path, SERVER_AUTH_ENDPOINT, "", 1) if code := req.URL.Query().Get("code"); code != "" { fmt.Printf("Asking server %s about code %s\n", serverAuth.ValidateUrl, code) gr := goreq.Request{ Method: "POST", Uri: serverAuth.ValidateUrl, ContentType: "application/x-www-form-urlencoded", Accept: "application/json", UserAgent: "Undergang/1.0", Body: "code=" + code + "&host=" + req.Host + "&path=" + originalPath, Timeout: 5 * time.Second, } var parsed struct { // Not really used. AccessToken string `json:"access_token"` } if ret, err := gr.Do(); err == nil && ret.StatusCode == 200 { if ret.Body.FromJsonTo(&parsed) == nil && parsed.AccessToken != "" { cookie := &http.Cookie{ Path: info.Prefix, Name: SERVER_AUTH_COOKIE, Value: NewTimestampSigner(sha1.New()).Sign(getCookieToken(info)), } http.SetCookie(w, cookie) fmt.Println("User authenticated!") http.Redirect(w, req, originalPath, 302) } else { respond(w, req, "Authentication server failure", http.StatusForbidden) } } else { respond(w, req, "Authentication server denied code", http.StatusForbidden) } } else { respond(w, req, "No code provided", http.StatusForbidden) } return true }
func AuthorizeRequest(path string, w http.ResponseWriter, r *http.Request, config Config) (result AuthResponse, err error) { if config.AuthURL == "" { result = AuthResponse{path, false, false} return } username, password, ok := basicAuth(r) if !ok { err = errors.New("No HTTP credentials were supplied. Issuing challenge.") writeChallenge(w) return } reqBody, err := json.Marshal(map[string]string{"username": username, "password": password, "path": path}) if err != nil { log.Println(err) return } req := goreq.Request{ Method: "POST", Uri: config.AuthURL, ContentType: "application/json", Accept: "application/json", Body: reqBody, Timeout: 3000 * time.Millisecond, } res, err := req.Do() if err != nil { return } switch res.StatusCode { case 200, 201: res.Body.FromJsonTo(&result) case 204: result = AuthResponse{path, false, false} case 401, 403: body, er := res.Body.ToString() if er != nil { body = "Unauthorized" } err = AuthError{res.StatusCode, body} case 404: err = AuthError{res.StatusCode, "The repository could not be found"} default: err = AuthError{res.StatusCode, "An unknown error occurred"} } return }
// buildCommonRequestProps is an internal method to set common properties of requests that will send to OpsGenie. func (cli *OpsGenieClient) buildCommonRequestProps() goreq.Request { if cli.httpTransportSettings == nil { cli.makeHTTPTransportSettings() } goreq.SetConnectTimeout(cli.httpTransportSettings.ConnectionTimeout) req := goreq.Request{} if cli.proxy != nil { req.Proxy = cli.proxy.toString() } req.UserAgent = userAgentParam.ToString() req.Timeout = cli.httpTransportSettings.RequestTimeout req.Insecure = true return req }
func doLookup(host string, path string) *PathInfo { uri := externalLookupUrl + "?host=" + url.QueryEscape(host) + "&path=" + url.QueryEscape(path) log.Printf("Asking %s about pathinfo\n", uri) req := goreq.Request{ Uri: uri, Accept: "application/json", UserAgent: "Undergang/1.0", Timeout: 5 * time.Second, } if ret, err := req.Do(); err == nil && ret.StatusCode == 200 { var path PathInfo ret.Body.FromJsonTo(&path) return &path } return nil }
func main() { flag.Parse() if *eaddr == "" || *topic == "" || *channel == "" { log.Println("Please input the elastic addr or topic or channel") return } res, err := goreq.Request{Uri: *eaddr + "?topic=" + *topic + "&channel=" + *channel}.Do() if err != nil { log.Println(err.Error()) } var v models.NodeItem body, _ := res.Body.ToString() log.Println(body) err = json.Unmarshal([]byte(body), &v) if err != nil { log.Fatal(err.Error()) } addr = v.Ip + ":" + strconv.Itoa(v.Tcpport) consumer, err = nsq.NewConsumer(*topic, *channel, cfg) if err != nil { log.Fatal(err.Error()) } consumer.AddHandler(nsq.HandlerFunc(func(m *nsq.Message) error { log.Println(string(m.Body)) return nil })) consumer.ConnectToNSQD(addr) <-exitchan }
func main() { item := Item{Id: 1111, Name: "foobar"} res, err := goreq.Request{ Method: "POST", Uri: "http://www.google.com", Body: item, }.Do() if err != nil { fmt.Println("Something wrong ", err.Error()) } else { spew.Dump(res.Header) fmt.Println(res.Body.ToString()) } }
func apiRequestBase(authToken string) *goreq.Request { req := goreq.Request{ Uri: apiURL(), ShowDebug: debugging, Insecure: !shouldVerifyHost(apiURL()), } if authToken != "" { req.AddHeader("Authorization", "Bearer "+authToken) } if os.Getenv("HEROKU_HEADERS") != "" { var h map[string]string json.Unmarshal([]byte(os.Getenv("HEROKU_HEADERS")), &h) for k, v := range h { req.AddHeader(k, v) } } return &req }
func apiRequest(authToken string) *goreq.Request { req := goreq.Request{ Uri: "https://" + apiHost(), Accept: "application/vnd.heroku+json; version=3", ShowDebug: debugging, Insecure: !shouldVerifyHost(apiHost()), } if authToken != "" { req.AddHeader("Authorization", "Bearer "+authToken) } if os.Getenv("HEROKU_HEADERS") != "" { var h map[string]string json.Unmarshal([]byte(os.Getenv("HEROKU_HEADERS")), &h) for k, v := range h { req.AddHeader(k, v) } } return &req }
func Del() { item := DelSolr{} item.Del.Query = `title:cyeam.com` item.Del.CommitWithin = 1000 req := goreq.Request{ Method: "POST", Uri: "http:///solr/post/update?wt=json", ContentType: "application/json", Body: item, // Proxy: "http://127.0.0.1:8888", } res, err := req.Do() if err != nil { fmt.Println(err, "*****") return } str, _ := res.Body.ToString() fmt.Println("del success", str) }
func Add() { item := AddSolr{} item.Add.Doc.Link = time.Now().String() item.Add.Doc.Title = "cyeam.com" item.Add.Overwrite = true item.Add.CommitWithin = 1000 req := goreq.Request{ Method: "POST", Uri: "http:///solr/post/update?wt=json", ContentType: "application/json", Body: item, // Proxy: "http://127.0.0.1:8888", } res, err := req.Do() if err != nil { fmt.Println(err, "*****") return } str, _ := res.Body.ToString() fmt.Println("add success", str) }
func (c *HTTPClient) MakeRequest(args Args) (http.Header, int, []byte, error) { header := make(map[string][]string) url, err := url.Parse(c.Host) if err != nil { return header, 0, []byte{}, errors.NewInvalidHostError(err) } url.Path = args.Path req := goreq.Request{ Uri: url.String(), Method: args.Method, Body: args.Body, Timeout: args.Timeout, ShowDebug: args.ShowDebug, } for name, value := range args.Headers { for _, v := range value { req.AddHeader(name, v) } } resp, err := req.Do() if err != nil { return header, 0, []byte{}, errors.NewRequestError(err) } respBody, err := ioutil.ReadAll(resp.Body) if err != nil { return resp.Header, resp.StatusCode, []byte{}, errors.NewResponseError(err) } if resp.StatusCode == args.AcceptableCode { return resp.Header, resp.StatusCode, respBody, nil } return resp.Header, resp.StatusCode, respBody, errors.NewResponseError(errors.ErrBadResponse) }
// POST http://localhost:8085/users // {"name":"user name"} // func (u *UserGraphResource) createUser(request *restful.Request, response *restful.Response) { obj := new(Object) err := request.ReadEntity(&obj.Data.User) if err != nil { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) return } res, err := goreq.Request{ Method: "POST", Body: obj, Uri: u.baseUrl, Accept: "application/json", ContentType: "application/json", }.Do() if err != nil { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) return } if res.StatusCode != 201 { response.AddHeader("Content-Type", "text/plain") value, _ := res.Body.ToString() response.WriteErrorString(http.StatusInternalServerError, "Object store returned: "+ strconv.Itoa(res.StatusCode)+" Response body:\n"+value) return } res.Body.FromJsonTo(&obj) res.Body.Close() user := obj.Data.User user.Id = obj.Id response.WriteHeader(http.StatusCreated) response.WriteEntity(user) }
// SendRequest sends the requested package (as a POST) to the defined func (n NotificationsManager) SendRequest(wait bool, count int, notification interface{}) { if wait { if count < 3 { time.Sleep(10 * time.Second) } else { log.Error("Too many notification attempts, aborting.") return } } req := goreq.Request{ Method: "POST", Uri: n.OAuthKeyChangeURL, UserAgent: "Tyk-Gatewy-Notifications", ContentType: "application/json", Body: notification, } req.AddHeader("X-Tyk-Shared-Secret", n.SharedSecret) resp, reqErr := req.Do() if reqErr != nil { log.Error("Request failed, trying again in 10s. Error was: ", reqErr) count++ go n.SendRequest(true, count, notification) return } if resp.StatusCode != 200 { log.Error("Request returned non-200 status, trying again in 10s.") count++ go n.SendRequest(true, count, notification) return } }
// MakeRequest makes an HTTP request. // The caller is in charge of closing the response body. ( #todo: is this proper? ) func MakeRequest(req goreq.Request) (*Response, error) { start := time.Now() resp, err := req.Do() if err != nil { Metrics.Error(err, "failed to make a request") return nil, err } since := time.Since(start) r := &Response{ Duration: since, Response: resp, } Metrics.TrackResponse(&req, since) if resp.StatusCode != 200 { Metrics.Error(nil, string(resp.StatusCode)) } return r, nil }
func (cli *OpsGenieIntegrationClient) buildRequest(method string, uri string, body interface{}) goreq.Request { req := goreq.Request{} req.Method = method req.Uri = uri if body != nil { req.Body = body } if cli.proxy != "" { req.Proxy = cli.proxy } req.UserAgent = userAgentParam.ToString() return req }
// Spawn sends the actual request. func (r *Request) Spawn(parent *Response, wg *sync.WaitGroup) { body := "" if r.Data != nil { body = r.Data.Format(parent) } greq := goreq.Request{Method: r.Method, Body: body, UserAgent: profile.UserAgent} // Let's set the headers, if needed. if r.Headers != nil { for _, line := range strings.Split(r.Headers.Format(parent), "\n") { line = strings.TrimSpace(line) if line == "" { continue } hdr := strings.Split(line, ":") greq.AddHeader(strings.TrimSpace(hdr[0]), strings.TrimSpace(hdr[1])) } } // Let's also add the cookies. if r.FwdCookies && parent != nil { if parent.cookies != nil { for _, delicacy := range parent.cookies { greq.AddCookie(delicacy) } } } // One go routine which pops responses from the channel and moves them to the list. go func() { for { r.doneReqs = append(r.doneReqs, <-r.doneChan) r.doneWg.Done() perc := float64(len(r.doneReqs)) / float64(r.Repeat) notify := false if perc >= 0.75 && perc-0.75 < 1e-4 { notify = true } else if perc >= 0.5 && perc-0.5 < 1e-4 { notify = true } else if perc >= 0.25 && perc-0.25 < 1e-4 { notify = true } else if len(r.doneReqs)%100 == 0 { notify = true } if notify { log.Notice("Completed %d requests out of %d to %s.", len(r.doneReqs), r.Repeat, r.URL) } } }() // Let's spawn all the requests, with their respective concurrency. wg.Add(r.Repeat) r.doneWg.Add(r.Repeat) for rno := 1; rno <= r.Repeat; rno++ { go func(no int, greq goreq.Request) { r.ongoingReqs <- struct{}{} // Adding sentinel value to limit concurrency. greq.Uri = r.URL.Generate() resp := Response{} startTime := time.Now() gresp, err := greq.Do() resp.FromGoResp(gresp, err, startTime) if err != nil { log.Critical("could not send request to #%d %s: %s", no, r.URL, err) } <-r.ongoingReqs // We're done, let's make room for the next request. resp.duration = time.Since(startTime) // Let's add that request to the list of completed requests. r.doneChan <- &resp runtime.Gosched() }(rno, greq) } // Let's now have a go routine which waits for all the requests to complete // and spawns all the children. go func() { r.doneWg.Wait() if r.Children != nil { log.Debug("Spawning children for %s.", r.URL) for _, child := range r.Children { // Note that we always use the LAST response as the parent response. child.Spawn(r.doneReqs[0], wg) } } log.Debug("Computing result of %s.", r.URL) r.ComputeResult(wg) }() }
func TestContactsRoute(t *testing.T) { Convey("Given a working account", t, func() { account := &models.Account{ Resource: models.MakeResource("", "johnorange2"), Status: "complete", AltEmail: "*****@*****.**", } err := account.SetPassword("fruityloops") So(err, ShouldBeNil) err = env.Accounts.Insert(account) So(err, ShouldBeNil) result, err := goreq.Request{ Method: "POST", Uri: server.URL + "/tokens", ContentType: "application/json", Body: `{ "type": "auth", "username": "******", "password": "******" }`, }.Do() So(err, ShouldBeNil) var response routes.TokensCreateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeTrue) authToken := response.Token Convey("Creating a contact with missing parts should fail", func() { request := goreq.Request{ Method: "POST", Uri: server.URL + "/contacts", ContentType: "application/json", Body: `{ "data": "` + uniuri.NewLen(64) + `", "encoding": "json", "version_major": 1, "version_minor": 0, "pgp_fingerprints": ["` + uniuri.New() + `"] }`, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsCreateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Message, ShouldEqual, "Invalid request") So(response.Success, ShouldBeFalse) }) Convey("Creating a contact with invalid input data should fail", func() { request := goreq.Request{ Method: "POST", Uri: server.URL + "/contacts", ContentType: "application/json", Body: "!@#!@#!@#", } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsCreateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Message, ShouldEqual, "Invalid input format") So(response.Success, ShouldBeFalse) }) Convey("Getting a non-owned contact should fail", func() { contact := &models.Contact{ Encrypted: models.Encrypted{ Encoding: "json", Data: uniuri.NewLen(64), Schema: "contact", VersionMajor: 1, VersionMinor: 0, }, Resource: models.MakeResource("not", uniuri.New()), } err := env.Contacts.Insert(contact) So(err, ShouldBeNil) request := goreq.Request{ Method: "GET", Uri: server.URL + "/contacts/" + contact.ID, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsGetResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Contact not found") Convey("Update of a not-owned contact should fail", func() { request := goreq.Request{ Method: "PUT", Uri: server.URL + "/contacts/" + contact.ID, ContentType: "application/json", Body: `{ "data": "` + uniuri.NewLen(64) + `", "name": "` + uniuri.New() + `", "encoding": "xml", "version_major": 8, "version_minor": 3 }`, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsUpdateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Contact not found") }) Convey("Deleting it should fail", func() { request := goreq.Request{ Method: "DELETE", Uri: server.URL + "/contacts/" + contact.ID, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsDeleteResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Contact not found") }) }) Convey("Getting a non-existing contact should fail", func() { request := goreq.Request{ Method: "GET", Uri: server.URL + "/contacts/" + uniuri.New(), } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsGetResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Contact not found") }) Convey("Creating a contact should succeed", func() { request := goreq.Request{ Method: "POST", Uri: server.URL + "/contacts", ContentType: "application/json", Body: `{ "data": "` + uniuri.NewLen(64) + `", "name": "` + uniuri.New() + `", "encoding": "json", "version_major": 1, "version_minor": 0, "pgp_fingerprints": ["` + uniuri.New() + `"] }`, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsCreateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Message, ShouldEqual, "A new contact was successfully created") So(response.Success, ShouldBeTrue) So(response.Contact.ID, ShouldNotBeNil) contact := response.Contact Convey("The contact should be visible on the list", func() { request := goreq.Request{ Method: "GET", Uri: server.URL + "/contacts", } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsListResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(len(*response.Contacts), ShouldBeGreaterThan, 0) So(response.Success, ShouldBeTrue) found := false for _, c := range *response.Contacts { if c.ID == contact.ID { found = true break } } So(found, ShouldBeTrue) }) Convey("Getting that contact should succeed", func() { request := goreq.Request{ Method: "GET", Uri: server.URL + "/contacts/" + contact.ID, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsGetResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeTrue) So(response.Contact.Name, ShouldEqual, contact.Name) }) Convey("Updating that contact should succeed", func() { newName := uniuri.New() request := goreq.Request{ Method: "PUT", Uri: server.URL + "/contacts/" + contact.ID, ContentType: "application/json", Body: `{ "data": "` + uniuri.NewLen(64) + `", "name": "` + newName + `", "encoding": "xml", "version_major": 8, "version_minor": 3 }`, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsUpdateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeTrue) So(response.Contact.Name, ShouldEqual, newName) }) Convey("Deleting that contact should succeed", func() { request := goreq.Request{ Method: "DELETE", Uri: server.URL + "/contacts/" + contact.ID, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsDeleteResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeTrue) So(response.Message, ShouldEqual, "Contact successfully removed") }) }) Convey("Update with invalid input should fail", func() { request := goreq.Request{ Method: "PUT", Uri: server.URL + "/contacts/" + uniuri.New(), ContentType: "application/json", Body: "123123!@#!@#", } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsUpdateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Invalid input format") }) Convey("Update of a non-existing contact should fail", func() { request := goreq.Request{ Method: "PUT", Uri: server.URL + "/contacts/gibberish", ContentType: "application/json", Body: `{ "data": "` + uniuri.NewLen(64) + `", "name": "` + uniuri.New() + `", "encoding": "xml", "version_major": 8, "version_minor": 3 }`, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsUpdateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Contact not found") }) Convey("Deleting a non-existing contact should fail", func() { request := goreq.Request{ Method: "DELETE", Uri: server.URL + "/contacts/gibberish", } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.ContactsDeleteResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Contact not found") }) }) }
func TestKeysRoute(t *testing.T) { Convey("Given a working account", t, func() { account := &models.Account{ Resource: models.MakeResource("", "johnorange4"), Status: "complete", AltEmail: "*****@*****.**", } err := account.SetPassword("fruityloops") So(err, ShouldBeNil) err = env.Accounts.Insert(account) So(err, ShouldBeNil) result, err := goreq.Request{ Method: "POST", Uri: server.URL + "/tokens", ContentType: "application/json", Body: `{ "type": "auth", "username": "******", "password": "******" }`, }.Do() So(err, ShouldBeNil) var response routes.TokensCreateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeTrue) authToken := response.Token Convey("Uploading a new key using an invalid JSON format should fail", func() { request := goreq.Request{ Method: "POST", Uri: server.URL + "/keys", ContentType: "application/json", Body: "!@#!@!@#", } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.KeysCreateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Message, ShouldEqual, "Invalid input format") So(response.Success, ShouldBeFalse) }) Convey("Uploading an invalid key should fail", func() { request := goreq.Request{ Method: "POST", Uri: server.URL + "/keys", ContentType: "application/json", Body: `{ "key": "hbnjmvnbhvm nbhm jhbjmnghnbgjvgbhvf bgvmj gvhnft" }`, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.KeysCreateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Message, ShouldEqual, "Invalid key format") So(response.Success, ShouldBeFalse) }) Convey("Uploading a key should succeed", func() { request := goreq.Request{ Method: "POST", Uri: server.URL + "/keys", ContentType: "application/json", Body: `{ "key": "` + strings.Join(strings.Split(`-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1 mQINBFR6JFoBEADoLOVi5NEkIELYOIfOsztAuPqNPiJcDXCsKuprjNj7n2vxyNim WbArRZ4TJereG0H2skCQlKMx26EiHHdK3je4i6erD+OT4NolAsxVsl4PpkEDZnzz tIwVb7FymahIrqwP9YPrXc0tr07HgnE3+it828ZJlCMfGUgJJrn12p+UetlBoFwr OEgaCl4fOfAuUQUz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nXpbFI2NBn3YwB2fulim8TZL03 SvpiZD7TUiZKmUAOmVPoZJ+GUIE9lJtBrlOS5n0TkhmS14G3xPlex7jdJ63JFmME XZ9gDcgUOzG7pSneCYyHOLKGwTmLV3HXUSIAm/8bW2xJ7g+j9qr/c78D8ThUY+I0 0edCq+tL5rpnPYIusI3lzh4xeSMSSVCKB+Fhz9DFdD6pZC6E6KWlaoUgw1DdvfFC KFrEhGFPu80Y7zl77nME9Yg9JYrKlISZHtbT8mDduOXlJIyZxsIlg/bDhsN38HOE 3ZoAsJh/8Ui44b58x/u4P9uKDroCua/6sOb0JFuxPNZHc7Sjdy1S0md7YEW3vFyT 1H1XzRAOPLwJFoz4ymRz9COHTyzExycr/TIjoBG7v1nYOGUdqaTNU2/802LRQaE2 eUftQWTTiFoES4Z0vTKmKwq3CoP80Z5zTrcQf8CdMmTd9bu9kE3AvrK6OD0amxKw LNHuuVgP/KuG0U4M8A641mUjCt0ZvtDCcAgO90cQKdHsuiCkX/wFYGg+lCzwjtRZ UZSWZtUmAO12vjmUwGtRbp5xfdbV+PmIBRYe0iikrykoBy+FLw9yHlSCoey2ih6W =r/yh -----END PGP PUBLIC KEY BLOCK-----`, "\n"), "\\n") + `" }`, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.KeysCreateResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Message, ShouldEqual, "A new key has been successfully inserted") So(response.Success, ShouldBeTrue) So(response.Key.ID, ShouldNotBeNil) key := response.Key Convey("Key should be visible on the user's key list", func() { request := goreq.Request{ Method: "GET", Uri: server.URL + "/keys?user=johnorange4", } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.KeysListResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeTrue) So(len(*response.Keys), ShouldBeGreaterThan, 0) }) Convey("Getting that key should succeed", func() { request := goreq.Request{ Method: "GET", Uri: server.URL + "/keys/" + key.ID, } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.KeysGetResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeTrue) So(response.Key.ID, ShouldEqual, key.ID) }) }) Convey("Listing keys without passing a username should fail", func() { request := goreq.Request{ Method: "GET", Uri: server.URL + "/keys", } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.KeysListResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Invalid username") }) Convey("Getting a non-existing key should fail", func() { request := goreq.Request{ Method: "GET", Uri: server.URL + "/keys/123", } request.AddHeader("Authorization", "Bearer "+authToken.ID) result, err := request.Do() So(err, ShouldBeNil) var response routes.KeysGetResponse err = result.Body.FromJsonTo(&response) So(err, ShouldBeNil) So(response.Success, ShouldBeFalse) So(response.Message, ShouldEqual, "Requested key does not exist on our server") }) }) }