Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(411)

Unified Diff: client/internal/common/json.go

Issue 1135173003: Create packages client/internal/ retry and lhttp. (Closed) Base URL: git@github.com:luci/luci-go@3_UI
Patch Set: . Created 5 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: client/internal/common/json.go
diff --git a/client/internal/common/json.go b/client/internal/common/json.go
index e1907febe02e97e482fb97e81496708d9b6aa5c6..25819886a472fb5cb3f2a7ccd7e4c18b2f917dc7 100644
--- a/client/internal/common/json.go
+++ b/client/internal/common/json.go
@@ -5,71 +5,11 @@
package common
import (
- "bytes"
"encoding/json"
"fmt"
- "net/http"
"os"
- "strings"
)
-const jsonContentType = "application/json; charset=utf-8"
-
-// GetJSON does a simple HTTP GET on a JSON endpoint.
-//
-// Returns the status code and the error, if any.
-func GetJSON(c *http.Client, url string, out interface{}) (int, error) {
- if c == nil {
- c = http.DefaultClient
- }
- resp, err := c.Get(url)
- if err != nil {
- return 0, fmt.Errorf("couldn't resolve %s: %s", url, err)
- }
- return decodeJSONResponse(resp, url, out)
-}
-
-// PostJSON does a HTTP POST on a JSON endpoint.
-//
-// Returns the status code and the error, if any.
-func PostJSON(c *http.Client, url string, in, out interface{}) (int, error) {
- if c == nil {
- c = http.DefaultClient
- }
- if in == nil {
- in = map[string]string{}
- }
- encoded, err := json.Marshal(in)
- if err != nil {
- return 0, nil
- }
- resp, err := c.Post(url, jsonContentType, bytes.NewBuffer(encoded))
- if err != nil {
- return 0, fmt.Errorf("couldn't resolve %s: %s", url, err)
- }
- return decodeJSONResponse(resp, url, out)
-}
-
-func decodeJSONResponse(resp *http.Response, url string, out interface{}) (int, error) {
- defer resp.Body.Close()
- 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 {
- return resp.StatusCode, fmt.Errorf("bad response %s: %s", url, err)
- }
- ct := strings.ToLower(resp.Header.Get("Content-Type"))
- if ct != jsonContentType {
- return resp.StatusCode, fmt.Errorf("unexpected Content-Type, expected \"%s\", got \"%s\"", jsonContentType, ct)
- }
- if resp.StatusCode >= 400 {
- return resp.StatusCode, fmt.Errorf("http status %d", resp.StatusCode)
- }
- return resp.StatusCode, nil
-}
-
// ReadJSONFile reads a file and decode it as JSON.
func ReadJSONFile(filePath string, object interface{}) error {
f, err := os.Open(filePath)

Powered by Google App Engine
This is Rietveld 408576698