// TODO(vadimsh): Add retries on HTTP 500.
// fetchJSON fetches JSON document by making a request using given client.
351469
func fetchJSON(c context.Context, client *http.Client, val interface{}, f func() (*http.Request, error)) error {
	r, err := f()
	if err != nil {
		logging.Errorf(c, "auth: URL fetch failed - %s", err)
		return err
	}
	logging.Infof(c, "auth: %s %s", r.Method, r.URL)
	resp, err := ctxhttp.Do(c, client, r)
	if err != nil {
		logging.Errorf(c, "auth: URL fetch failed, can't connect - %s", err)
		return transient.Tag.Apply(err)
	}
	defer func() {
		ioutil.ReadAll(resp.Body)
		resp.Body.Close()
	}()
	if resp.StatusCode >= 300 {
		body, _ := ioutil.ReadAll(resp.Body)
		// Opportunistically try to unmarshal the response. Works with JSON APIs.
		if val != nil {
			json.Unmarshal(body, val)
		}
		logging.Errorf(c, "auth: URL fetch failed - HTTP %d - %s", resp.StatusCode, string(body))
		err := fmt.Errorf("auth: HTTP code (%d) when fetching %s", resp.StatusCode, r.URL)
		if resp.StatusCode >= 500 {
			return transient.Tag.Apply(err)
		}
		return err
	}
	if val != nil {
		if err = json.NewDecoder(resp.Body).Decode(val); err != nil {
			logging.Errorf(c, "auth: URL fetch failed, bad JSON - %s", err)
			return fmt.Errorf("auth: can't deserialize JSON at %q - %s", r.URL, err)
		}
	}
	return nil
}
144209
func (tf *defaultTokenFetcher) Fetch() (string, error) {
	tf.logger.Printf("[INFO] Getting auth token of %q from UAA (%s)", tf.username, tf.uaaAddr)
	client, err := uaago.NewClient(tf.uaaAddr)
	if err != nil {
		return "", err
	}

	resCh, errCh := make(chan string), make(chan error)
	go func() {
		token, err := client.GetAuthToken(tf.username, tf.password, tf.insecure)
		if err != nil {
			errCh <- err
		}
		resCh <- token
	}()

	timeout := defaultUAATimeout
	if tf.timeout != 0 {
		timeout = tf.timeout
	}

	select {
	case err := <-errCh:
		return "", err
	case <-time.After(timeout):
		return "", fmt.Errorf("request timeout: %s", timeout)
	case token := <-resCh:
		return token, nil
	}
}
546665
func ServeJSON(w http.ResponseWriter, err error) error {
	w.Header().Set("Content-Type", "application/json")
	var sc int

	switch errs := err.(type) {
	case Errors:
		if len(errs) < 1 {
			break
		}

		if err, ok := errs[0].(ErrorCoder); ok {
			sc = err.ErrorCode().Descriptor().HTTPStatusCode
		}
	case ErrorCoder:
		sc = errs.ErrorCode().Descriptor().HTTPStatusCode
		err = Errors{err} // create an envelope.
	default:
		// We just have an unhandled error type, so just place in an envelope
		// and move along.
		err = Errors{err}
	}

	if sc == 0 {
		sc = http.StatusInternalServerError
	}

	w.WriteHeader(sc)

	return json.NewEncoder(w).Encode(err)
}
740370
func FetchState(url string) (*catalog.ServicesState, error) {
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		return nil, fmt.Errorf("Bad status code on state fetch: %d", resp.StatusCode)
	}

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	state, err := catalog.Decode(bytes)
	if err != nil {
		return nil, err
	}

	return state, nil
}
648509
func (c *C) JSON(status int, v interface{}) {
	c.Writer.Header().Set(contentType, "application/json; charset=UTF-8")
	c.Writer.WriteHeader(status)
	if v == nil {
		return
	}

	buf := bufPool.Get()
	defer bufPool.Put(buf)

	if err := json.NewEncoder(buf).Encode(v); err != nil {
		panic(err)
	}

	c.Writer.Write(buf.Bytes())
}
1066635
func FetchHTTP(jwkurl string, options ...Option) (*Set, error) {
	var httpcl HTTPClient = http.DefaultClient
	for _, option := range options {
		switch option.Name() {
		case optkeyHTTPClient:
			httpcl = option.Value().(HTTPClient)
		}
	}

	res, err := httpcl.Get(jwkurl)
	if err != nil {
		return nil, errors.Wrap(err, "failed to fetch remote JWK")
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return nil, errors.New("failed to fetch remote JWK (status != 200)")
	}

	buf, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, errors.Wrap(err, "failed to read JWK HTTP response body")
	}

	return ParseBytes(buf)
}
328609
func (a *API) writeJSON(j interface{}, res http.ResponseWriter) {
	data, _ := json.Marshal(j)
	res.Header().Set("Content-Type", "application/json; charset=utf-8")
	res.Write(data)
}
1300516
func WriteJSON(w http.ResponseWriter, obj interface{}) error {
	writeContentType(w, jsonContentType)
	jsonBytes, err := json.Marshal(obj)
	if err != nil {
		return err
	}
	_, err = w.Write(jsonBytes)
	return err
}
1278327
func WriteJSON(w http.ResponseWriter, code int, v interface{}) error {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	buf, err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		return err
	}
	if _, err := w.Write(buf); err != nil {
		return err
	}
	return nil
	//return json.NewEncoder(w).Encode(v)
}
33508
func ReadJSON(resp *http.Response, out interface{}) error {
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}

		return fmt.Errorf("StatusCode: %d, Body: %s", resp.StatusCode, body)
	}

	if out == nil {
		io.Copy(ioutil.Discard, resp.Body)
		return nil
	}

	decoder := json.NewDecoder(resp.Body)
	return decoder.Decode(out)
}
739091
func (f *fetcher) Fetch() error {
	resp, err := f.client.Do(f.req)
	if err != nil {
		return errors.Trace(err)
	}

	defer func() {
		err = resp.Body.Close()
		if err != nil {
			logger.Debugf("failed defer %q", errors.Trace(err))
		}
	}()

	if resp.StatusCode != 200 {
		f.image.cleanup()
		return errors.NotFoundf(
			"got %d fetching image %q", resp.StatusCode, path.Base(
				f.req.URL.String()))
	}
	err = f.image.write(resp.Body, f.metadata)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
27275
func jsonMarshal(c *Client, r *Request, d interface{}) ([]byte, error) {
	if !r.jsonEscapeHTML {
		return noescapeJSONMarshal(d)
	} else if !c.jsonEscapeHTML {
		return noescapeJSONMarshal(d)
	}
	return c.JSONMarshal(d)
}
816726
func HttpGetJSON(client *http.Client, url string, v interface{}) error {
	rc, err := HttpGet(client, url, nil)
	if err != nil {
		return err
	}
	defer rc.Close()
	err = json.NewDecoder(rc).Decode(v)
	if _, ok := err.(*json.SyntaxError); ok {
		err = NotFoundError{"JSON syntax error at " + url}
	}
	return err
}
515922
func (ns *Namespace) GetJSON(urlParts ...string) (interface{}, error) {
	var v interface{}
	url := strings.Join(urlParts, "")
	cache := ns.cacheGetJSON

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, _errors.Wrapf(err, "Failed to create request for getJSON resource %s", url)
	}

	unmarshal := func(b []byte) (bool, error) {
		err := json.Unmarshal(b, &v)
		if err != nil {
			return true, err
		}
		return false, nil
	}

	req.Header.Add("Accept", "application/json")

	err = ns.getResource(cache, unmarshal, req)
	if err != nil {
		ns.deps.Log.ERROR.Printf("Failed to get JSON resource %q: %s", url, err)
		return nil, nil
	}

	return v, nil
}
1345974
func (p *Repository) GetJSON() string {
	p.Mutex.RLock()
	defer p.Mutex.RUnlock()

	result := api.Rules{}
	for _, r := range p.rules {
		result = append(result, &r.Rule)
	}

	return JSONMarshalRules(result)
}
610318
func NewRequestJSON(ctx context.Context, c *http.Client, rFn retry.Factory, url, method string, headers map[string]string, in, out interface{}) (func() (int, error), error) {
	var encoded []byte
	if in != nil {
		var err error
		if encoded, err = json.Marshal(in); err != nil {
			return nil, err
		}
	}

	return NewRequest(ctx, c, rFn, func() (*http.Request, error) {
		var body io.Reader
		if encoded != nil {
			body = bytes.NewReader(encoded)
		}

		req, err := http.NewRequest(method, url, body)
		if err != nil {
			return nil, err
		}
		if encoded != nil {
			req.Header.Set("Content-Type", jsonContentTypeForPOST)
		}
		if headers != nil {
			for k, v := range headers {
				req.Header.Add(k, v)
			}
		}
		return req, nil
	}, func(resp *http.Response) error {
		defer resp.Body.Close()
		if ct := strings.ToLower(resp.Header.Get("Content-Type")); !strings.HasPrefix(ct, jsonContentType) {
			// Non-retriable.
			return fmt.Errorf("unexpected Content-Type, expected \"%s\", got \"%s\"", jsonContentType, ct)
		}
		if out == nil {
			// The client doesn't care about the response. Still ensure the response
			// is valid json.
			out = &map[string]interface{}{}
		}
		if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
			// Retriable.
			return errors.Annotate(err, "bad response %s", url).Tag(transient.Tag).Err()
		}
		return nil
	}, nil), nil
}
1153908
func (s *Service) QueryRawJSON(ctx context.Context, req *query.Request) ([]byte, error) {
	resp, err := s.query(ctx, req)
	if err != nil {
		return nil, err
	}

	return ioutil.ReadAll(resp.Body)
}