func getTrips(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { sess, err := mgo.Dial(Url) if err != nil { fmt.Printf("Can't connect to mongo, go error %v\n", err) os.Exit(1) } defer sess.Close() sess.SetSafe(&mgo.Safe{}) collection := sess.DB("cmpe273").C("Trips") data := PostResParams{} id := p.ByName("trip_id") fmt.Println("id:", id) err = collection.Find(bson.M{"_id": bson.ObjectIdHex(id)}).Select(bson.M{}).One(&data) if err != nil { if err.Error() == "not found" { rw.WriteHeader(http.StatusNotFound) fmt.Fprintf(rw, http.StatusText(http.StatusNotFound)) } else { rw.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(rw, err.Error()) } } else { rw.WriteHeader(http.StatusCreated) fmt.Fprintf(rw, http.StatusText(http.StatusOK)) b, _ := json.Marshal(data) fmt.Println(string(b)) fmt.Fprintf(rw, "\n************************\n") fmt.Fprintf(rw, string(b)) fmt.Fprintf(rw, "\n************************\n") } }
func (ctl *controller) updateApp(c web.C, w http.ResponseWriter, r *http.Request) { app := api.Application{} if err := json.NewDecoder(r.Body).Decode(&app); err != nil { logger.Error("updateApp", "error", err) http.Error(w, http.StatusText(400), 400) return } app.ID = c.URLParams["app_id"] app.TeamID = c.Env["team_id"].(string) err := ctl.api.UpdateApp(&app) switch err { case nil: default: logger.Error("updatedApp", "error", err, "app", app) http.Error(w, http.StatusText(400), 400) return } appJSON, err := ctl.api.GetAppJSON(app.ID) if err != nil { logger.Error("updateApp", "error", err, "appID", app.ID) http.Error(w, http.StatusText(400), 400) return } w.Write(appJSON) }
func (ctl *controller) updateChannel(c web.C, w http.ResponseWriter, r *http.Request) { channel := api.Channel{} if err := json.NewDecoder(r.Body).Decode(&channel); err != nil { logger.Error("updateChannel", "error", err) http.Error(w, http.StatusText(400), 400) return } channel.ID = c.URLParams["channel_id"] channel.ApplicationID = c.URLParams["app_id"] err := ctl.api.UpdateChannel(&channel) switch err { case nil: default: logger.Error("updateChannel", "error", err, "channel", channel) http.Error(w, http.StatusText(400), 400) return } channelJSON, err := ctl.api.GetChannelJSON(channel.ID) if err != nil { logger.Error("updateChannel", "error", err, "channelID", channel.ID) http.Error(w, http.StatusText(400), 400) return } w.Write(channelJSON) }
func handlerLogger(fn Handler, w http.ResponseWriter, r *http.Request, p httprouter.Params) { l := NewHandlerLogEntry(r) l.Info("started handling request") starttime := time.Now() err := fn(w, r, p) duration := time.Since(starttime) l.Data["duration"] = duration code := http.StatusOK if err != nil { code = err.Code } l.Data["status"] = code l.Data["text_status"] = http.StatusText(code) if err != nil { if err.Error != nil { l.Data["error_message"] = err.Error l.Debug(errgo.Details(err.Error)) l.Error("completed handling request") scode := strconv.Itoa(err.Code) http.Error(w, scode+" ("+http.StatusText(err.Code)+") - "+err.Error.Error(), err.Code) } } else { l.Info("completed handling request") } }
func (v Validator) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, http.StatusText(405), 405) return } var resp ValidationResult render := func() { if err := json.NewEncoder(w).Encode(resp); err != nil { http.Error(w, http.StatusText(500), 500) } } jsonDoc := r.FormValue("json") resp.DocType = r.FormValue("doctype") schema, ok := v[r.FormValue("doctype")] if !ok { resp.Errors = []string{fmt.Sprintf("This document type schema not yet implemented: %q", r.FormValue("doctype"))} render() return } loader := js.NewStringLoader(jsonDoc) result, err := schema.Validate(loader) if err != nil { resp.Errors = []string{"JSON is not well-formed: " + err.Error()} } else { if result.Valid() { resp.Valid = true } else { for _, err := range result.Errors() { msg := err.Context.String() + ": " + err.Description resp.Errors = append(resp.Errors, msg) } } } render() }
func serveTemplate(w http.ResponseWriter, templateName string, data interface{}) { lp := path.Join("views", "layout.tmpl") fp := path.Join("views", templateName+".tmpl") // Return a 404 if the template doesn't exist info, err := os.Stat(fp) if err != nil { if os.IsNotExist(err) { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } } // Return a 404 if the request is for a directory if info.IsDir() { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } // Create the template tmpl, err := template.ParseFiles(lp, fp) if err != nil { log.Error("Failed to create the template:", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } // Execute the template and send it to the user if err := tmpl.ExecuteTemplate(w, "layout", data); err != nil { log.Error("Failed to execute the template:", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } }
func www_coffeecat_root(w http.ResponseWriter, r *http.Request) { f, err := os.Open("images/coffeecat") if err != nil { log.Print(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } images, err := f.Readdirnames(-1) if err != nil { log.Print(err) return } sort.Sort(sort.Reverse(sort.StringSlice(images))) last := -1 re := regexp.MustCompile("([0-9]+)[.]png$") for i := 0; i < len(images); i++ { m := re.FindStringSubmatch(images[i]) if len(m) == 2 { last, _ = strconv.Atoi(m[1]) break } } if last == -1 { log.Print("no images matches to regexp.") http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } http.Redirect(w, r, fmt.Sprintf("/coffeecat/%d", last), http.StatusFound) }
func TodoShow(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { log.Printf("NOT GET") http.Error(w, http.StatusText(405), 405) return } id := r.FormValue("id") if id == "" { log.Printf("Bad ID") http.Error(w, http.StatusText(400), 400) return } row := db.QueryRow("SELECT * FROM todos WHERE Id = $1", id) todo := new(Todo) err := row.Scan(&todo.Id, &todo.Name, &todo.Completed) if err == sql.ErrNoRows { http.NotFound(w, r) return } else if err != nil { http.Error(w, http.StatusText(500), 500) return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(todo); err != nil { log.Printf("Error printing todos") panic(err) } }
func TodoIndex(w http.ResponseWriter, r *http.Request) { rows, err := db.Query("SELECT * FROM todos") if err != nil { log.Printf("Error opening DB") http.Error(w, http.StatusText(500), 500) return } defer rows.Close() todos := make([]*Todo, 0) for rows.Next() { todo := new(Todo) err := rows.Scan(&todo.Id, &todo.Name, &todo.Completed) if err != nil { log.Printf("Error scanning DB") http.Error(w, http.StatusText(500), 500) return } todos = append(todos, todo) } if err = rows.Err(); err != nil { log.Printf("Error closing DB") http.Error(w, http.StatusText(500), 500) return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(todos); err != nil { log.Printf("Error printing todos") panic(err) } }
// ServeHTTP implementation of interface func authorized(w http.ResponseWriter, r *http.Request) bool { // Headers Authorization found ? hAuth := r.Header.Get("authorization") if hAuth == "" { w.Header().Set("WWW-Authenticate", "Basic realm=tmail REST server") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return false } // check credential if hAuth[:5] != "Basic" { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return false } decoded, err := base64.StdEncoding.DecodeString(hAuth[6:]) if err != nil { logError(r, "on decoding http auth credentials:", err.Error()) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return false } credentials := bytes.SplitN(decoded, []byte{58}, 2) if bytes.Compare([]byte(core.Cfg.GetRestServerLogin()), credentials[0]) != 0 || bytes.Compare([]byte(core.Cfg.GetRestServerPasswd()), credentials[1]) != 0 { logError(r, "bad authentification. Login:"******"password:", string(credentials[1])) http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return false } return true }
func proxyError(w http.ResponseWriter, err error, status int) { switch status { case http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusRequestTimeout, http.StatusGatewayTimeout, http.StatusGone: err = nil case 0: switch err { case format.ErrUnknownFormat, ErrTooSmall: status = http.StatusUnsupportedMediaType case ErrTooBig: status = http.StatusRequestEntityTooLarge default: if isTimeout(err) { err = nil status = http.StatusGatewayTimeout } else { status = http.StatusInternalServerError } } default: err = fmt.Errorf("Proxy received %d %s", status, http.StatusText(status)) status = http.StatusBadGateway } if err == nil { err = fmt.Errorf(http.StatusText(status)) } http.Error(w, err.Error(), status) }
// PUT /volume HTTP Handler func VolumeUpdateHandler(c web.C, w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) rbody := &volumeUpdateReqBody{} // Decode JSON err := decoder.Decode(&rbody) if err != nil { log.Debug(err) http.Error(w, http.StatusText(400), 400) return } // Validate res, err := v.ValidateStruct(rbody) if err != nil { log.Debug(res) http.Error(w, http.StatusText(422), 422) return } // Set the vol redis keys if err := events.PublishVolumeEvent(c.Env["REDIS"].(*redis.Client), rbody.Level); err != nil { log.Error(err) http.Error(w, http.StatusText(500), 500) return } // We got here! It's alllll good. w.WriteHeader(200) }
//CheckRegistrationSMSConfirmation is called by the sms code form to check if the sms is already confirmed on the mobile phone func (service *Service) CheckRegistrationSMSConfirmation(w http.ResponseWriter, request *http.Request) { registrationSession, err := service.GetSession(request, SessionForRegistration, "registrationdetails") if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } response := map[string]bool{} if registrationSession.IsNew { // todo: registrationSession is new with SMS, something must be wrong log.Warn("Registration is new") response["confirmed"] = true //This way the form will be submitted, let the form handler deal with redirect to login } else { validationkey, _ := registrationSession.Values["phonenumbervalidationkey"].(string) confirmed, err := service.phonenumberValidationService.IsConfirmed(request, validationkey) if err == validation.ErrInvalidOrExpiredKey { confirmed = true //This way the form will be submitted, let the form handler deal with redirect to login return } if err != nil { log.Error(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } response["confirmed"] = confirmed } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(response) }
func (b *ContainerBackup) request(method, path string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest(method, path, body) if err != nil { return nil, err } conn, err := net.Dial(b.proto, b.addr) if err != nil { return nil, err } clientconn := httputil.NewClientConn(conn, nil) resp, err := clientconn.Do(req) if err != nil { return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 400 { body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if len(body) == 0 { return nil, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode)) } return nil, fmt.Errorf("HTTP %s: %s", http.StatusText(resp.StatusCode), body) } return resp, nil }
// OnPanic is called when panic occur. func (ja *jsonAPI) OnPanic(w http.ResponseWriter, r *http.Request) { // if api.SafeWriter.Write called before occuring panic, // this will not write response body and header. // Because it is meaningless and foolish that jsonplugin.OnPanic break response body. // Example: Write([]byte("{}") -> some proccess -> panic -> jsonplugin.OnPanic -> Write([]byte(`{"message": "Internal Server Error"}`)) // -> Response body is {}{"message": "Internal Server Error"}. if sw, ok := w.(*dou.SafeWriter); ok { if sw.Wrote { return } } var b string j, err := json.Marshal(map[string]string{"message": http.StatusText(http.StatusInternalServerError)}) if err != nil { w.Header().Set("Content-Type", "text/plain; charset=utf-8") b = http.StatusText(http.StatusInternalServerError) } else { b = string(j) } w.WriteHeader(http.StatusInternalServerError) _, err = fmt.Fprintln(w, b) if err != nil { // Skip error // http.Error skip this error too. log.Printf("dou: fail to fmt.Fpintln(http.ResponseWriter, string)\n%v", err) } }
func (this *HttpError) Error() string { if this.Message != "" { return fmt.Sprintf("%d %s - %s", this.Code, http.StatusText(this.Code), this.Message) } return fmt.Sprintf("%d %s", this.Code, http.StatusText(this.Code)) }
// Error returns a string representation of the error. func (e *Error) Error() string { if e.Details != nil && e.Details.Reason != "" { return fmt.Sprintf("elastic: Error %d (%s): %s [type=%s]", e.Status, http.StatusText(e.Status), e.Details.Reason, e.Details.Type) } else { return fmt.Sprintf("elastic: Error %d (%s)", e.Status, http.StatusText(e.Status)) } }
func todosIndex(w http.ResponseWriter, r *http.Request) { rows, err := db.Query("SELECT * FROM todo") if err != nil { http.Error(w, http.StatusText(500), 500) return } defer rows.Close() todos := make([]*Todo, 0) for rows.Next() { todo := new(Todo) err := rows.Scan(&todo.Id, &todo.Title, &todo.Description, &todo.Created_at) if err != nil { http.Error(w, http.StatusText(500), 500) return } todos = append(todos, todo) } if err = rows.Err(); err != nil { http.Error(w, http.StatusText(500), 500) return } indexTemplate(w, r, todos) }
// www_coffeecat is little special, because it automatically put image files. func www_coffeecat(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") f, err := os.Open("images/coffeecat") if err != nil { log.Print(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } images, err := f.Readdirnames(-1) if err != nil { log.Print(err) return } sort.Strings(images) for i, img := range images { images[i] = filepath.Join("images/coffeecat", img) } if r.URL.Path == "/coffeecat/" { www_coffeecat_root(w, r) } else { subURL := r.URL.Path[len("/coffeecat/"):] // sub url should convertable to int // ex) r.URL.Path == "/coffeecat/0" i, err := strconv.Atoi(subURL) if err != nil { log.Print(err) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } www_coffeecat_page(w, r, i) } }
func indexTemplate(w http.ResponseWriter, r *http.Request, todos []*Todo) { lp := path.Join("templates", "layout.html") fp := path.Join("templates", "index.html") // Return a 404 if the template doesn't exist info, err := os.Stat(fp) if err != nil { if os.IsNotExist(err) { http.NotFound(w, r) return } } // Return a 404 if the request is for a directory if info.IsDir() { http.NotFound(w, r) return } tmpl, err := template.ParseFiles(lp, fp) if err != nil { // Log the detailed error log.Println(err.Error()) // Return a generic "Internal Server Error" message http.Error(w, http.StatusText(500), 500) return } if err := tmpl.ExecuteTemplate(w, "layout", todos); err != nil { log.Println(err.Error()) http.Error(w, http.StatusText(500), 500) } }
func www_coffeecat_page(w http.ResponseWriter, r *http.Request, i int) { img := fmt.Sprintf("images/coffeecat/%02d.png", i) _, err := os.Stat(img) if err != nil { if os.IsNotExist(err) { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } else { log.Print(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } } prev := fmt.Sprintf("coffeecat/%d", i-1) _, err = os.Stat(fmt.Sprintf("images/coffeecat/%02d.png", i-1)) if err != nil { if os.IsNotExist(err) { prev = "" } else { log.Print(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } } next := fmt.Sprintf("coffeecat/%d", i+1) _, err = os.Stat(fmt.Sprintf("images/coffeecat/%02d.png", i+1)) if err != nil { if os.IsNotExist(err) { next = "" } else { log.Print(err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } } fmap := template.FuncMap{ "lower": strings.ToLower, } t, err := template.New("coffeecat_page.html").Funcs(fmap).ParseFiles("template/coffeecat_page.html", "template/head.html", "template/menu.html", "template/footer.html") if err != nil { log.Fatal(err) } info := struct { Menus []string MenuOn string Image string Prev string Next string }{ Menus: Menus, MenuOn: "CoffeeCat", Image: img, Prev: prev, Next: next, } err = t.Execute(w, info) if err != nil { log.Fatal(err) } }
func handleHi(w http.ResponseWriter, r *http.Request) { start := time.Now() requests.Add(1) // COUNTER // Perform a "database" "lookup". backend_start := time.Now() randLock.Lock() // golang issue 3611 time.Sleep(time.Duration(zipf.Uint64()) * time.Millisecond) randLock.Unlock() backend_latency_ms.Observe(float64(time.Since(backend_start).Nanoseconds() / 1e6)) // HISTOGRAM // Fail sometimes. switch v := rand.Intn(100); { case v > 95: errors.WithLabelValues(http.StatusText(500)).Add(1) // MAP w.WriteHeader(500) return case v > 85: errors.WithLabelValues(http.StatusText(400)).Add(1) // MAP w.WriteHeader(400) return } // Record metrics. defer func() { l := time.Since(start) ms := float64(l.Nanoseconds()) / 1e6 latency_ms.Observe(ms) // HISTOGRAM }() // Return page content. w.Write([]byte("hi\n")) }
func TestError(t *testing.T) { ret403 := response551.Error(403, "アクセスするには会員登録をおこないログインする必要があります。") ret404 := response551.Error(404, "指定されたカテゴリーは存在しません。") if ret403.Code() != 403 { t.Error("エラーレスポンス構造体の生成に失敗しました。") } if ret403.Text() != http.StatusText(403) { t.Error("エラーレスポンス構造体の生成に失敗しました。") } if ret403.Message() != "アクセスするには会員登録をおこないログインする必要があります。" { t.Error("エラーレスポンス構造体の生成に失敗しました。") } if ret403.String() != "アクセスするには会員登録をおこないログインする必要があります。" { t.Error("エラーレスポンス構造体の生成に失敗しました。") } if ret404.Code() != 404 { t.Error("エラーレスポンス構造体の生成に失敗しました。") } if ret404.Text() != http.StatusText(404) { t.Error("エラーレスポンス構造体の生成に失敗しました。") } if ret404.Message() != "指定されたカテゴリーは存在しません。" { t.Error("エラーレスポンス構造体の生成に失敗しました。") } if ret404.String() != "指定されたカテゴリーは存在しません。" { t.Error("エラーレスポンス構造体の生成に失敗しました。") } if fmt.Sprint(ret404) != "指定されたカテゴリーは存在しません。" { t.Error("エラーレスポンス構造体の生成に失敗しました。") } }
// Get ... func (t *TargetAPI) Get() { id := t.GetIDFromURL() target, err := dao.GetRepTarget(id) if err != nil { log.Errorf("failed to get target %d: %v", id, err) t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } if target == nil { t.CustomAbort(http.StatusNotFound, http.StatusText(http.StatusNotFound)) } // The reason why the password is returned is that when user just wants to // modify other fields of target he does not need to input the password again. // The security issue can be fixed by enable https. if len(target.Password) != 0 { pwd, err := utils.ReversibleDecrypt(target.Password, t.secretKey) if err != nil { log.Errorf("failed to decrypt password: %v", err) t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } target.Password = pwd } t.Data["json"] = target t.ServeJSON() }
func (ctl *controller) addApp(c web.C, w http.ResponseWriter, r *http.Request) { sourceAppID := r.URL.Query().Get("clone_from") app := api.Application{} if err := json.NewDecoder(r.Body).Decode(&app); err != nil { logger.Error("addApp", "error", err) http.Error(w, http.StatusText(400), 400) return } app.TeamID = c.Env["team_id"].(string) _, err := ctl.api.AddAppCloning(&app, sourceAppID) switch err { case nil: default: logger.Error("addApp", "error", err, "app", app) http.Error(w, http.StatusText(400), 400) return } appJSON, err := ctl.api.GetAppJSON(app.ID) if err != nil { logger.Error("addApp", "error", err, "appID", app.ID) http.Error(w, http.StatusText(400), 400) return } w.Write(appJSON) }
// List ... func (t *TargetAPI) List() { name := t.GetString("name") targets, err := dao.FilterRepTargets(name) if err != nil { log.Errorf("failed to filter targets %s: %v", name, err) t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } for _, target := range targets { if len(target.Password) == 0 { continue } str, err := utils.ReversibleDecrypt(target.Password, t.secretKey) if err != nil { log.Errorf("failed to decrypt password: %v", err) t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } target.Password = str } t.Data["json"] = targets t.ServeJSON() return }
func (ctl *controller) updateGroup(c web.C, w http.ResponseWriter, r *http.Request) { group := api.Group{} if err := json.NewDecoder(r.Body).Decode(&group); err != nil { logger.Error("updateGroup", "error", err) http.Error(w, http.StatusText(400), 400) return } group.ID = c.URLParams["group_id"] group.ApplicationID = c.URLParams["app_id"] err := ctl.api.UpdateGroup(&group) switch err { case nil: default: logger.Error("updateGroup", "error", err, "group", group) http.Error(w, http.StatusText(400), 400) return } groupJSON, err := ctl.api.GetGroupJSON(group.ID) if err != nil { logger.Error("updateGroup", "error", err, "groupID", group.ID) http.Error(w, http.StatusText(400), 400) return } w.Write(groupJSON) }
// Delete ... func (t *TargetAPI) Delete() { id := t.GetIDFromURL() target, err := dao.GetRepTarget(id) if err != nil { log.Errorf("failed to get target %d: %v", id, err) t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } if target == nil { t.CustomAbort(http.StatusNotFound, http.StatusText(http.StatusNotFound)) } policies, err := dao.GetRepPolicyByTarget(id) if err != nil { log.Errorf("failed to get policies according target %d: %v", id, err) t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } if len(policies) > 0 { t.CustomAbort(http.StatusBadRequest, "the target is used by policies, can not be deleted") } if err = dao.DeleteRepTarget(id); err != nil { log.Errorf("failed to delete target %d: %v", id, err) t.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) } }
func (ctl *controller) updatePackage(c web.C, w http.ResponseWriter, r *http.Request) { pkg := api.Package{} if err := json.NewDecoder(r.Body).Decode(&pkg); err != nil { logger.Error("updatePackage", "error", err) http.Error(w, http.StatusText(400), 400) return } pkg.ID = c.URLParams["package_id"] pkg.ApplicationID = c.URLParams["app_id"] err := ctl.api.UpdatePackage(&pkg) switch err { case nil: default: logger.Error("updatePackage", "error", err, "package", pkg) http.Error(w, http.StatusText(400), 400) return } pkgJSON, err := ctl.api.GetPackageJSON(pkg.ID) if err != nil { logger.Error("updatePackage", "error", err, "packageID", pkg.ID) http.Error(w, http.StatusText(400), 400) return } w.Write(pkgJSON) }
// SendHandler is a request handler to send service request using HTTP client. func SendHandler(r *Request) { var err error r.HTTPResponse, err = r.Service.Config.HTTPClient.Do(r.HTTPRequest) if err != nil { // Capture the case where url.Error is returned for error processing // response. e.g. 301 without location header comes back as string // error and r.HTTPResponse is nil. Other url redirect errors will // comeback in a similar method. if e, ok := err.(*url.Error); ok { if s := reStatusCode.FindStringSubmatch(e.Error()); s != nil { code, _ := strconv.ParseInt(s[1], 10, 64) r.HTTPResponse = &http.Response{ StatusCode: int(code), Status: http.StatusText(int(code)), Body: ioutil.NopCloser(bytes.NewReader([]byte{})), } return } } if r.HTTPRequest == nil { // Add a dummy request response object to ensure the HTTPResponse // value is consistent. r.HTTPResponse = &http.Response{ StatusCode: int(0), Status: http.StatusText(int(0)), Body: ioutil.NopCloser(bytes.NewReader([]byte{})), } } // Catch all other request errors. r.Error = apierr.New("RequestError", "send request failed", err) r.Retryable.Set(true) // network errors are retryable } }