Created
December 7, 2014 14:46
-
-
Save hirokazumiyaji/401416759c29a49d1c58 to your computer and use it in GitHub Desktop.
json request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"os" | |
"github.com/k0kubun/pp" | |
) | |
func Usage() { | |
fmt.Fprintln(os.Stderr, "req <url> [options]") | |
flag.PrintDefaults() | |
} | |
func errorProcess(err error) { | |
fmt.Println("\033[35m", err, "\033[0m") | |
os.Exit(1) | |
} | |
func main() { | |
if len(os.Args) < 1 { | |
Usage() | |
os.Exit(0) | |
} | |
url := os.Args[1] | |
var postData string | |
f := flag.NewFlagSet(os.Args[0], flag.ExitOnError) | |
f.StringVar(&postData, "d", "", "post data") | |
f.Parse(os.Args[1:]) | |
for 0 < f.NArg() { | |
f.Parse(f.Args()[1:]) | |
} | |
client := http.Client{} | |
if postData == "" { | |
var data map[string]interface{} | |
req, err := http.NewRequest("GET", url, nil) | |
req.Header.Add("Content-Type", "application/json; charset=utf-8") | |
res, err := client.Do(req) | |
if err != nil { | |
errorProcess(err) | |
} | |
pp.Println("========== res ==========") | |
pp.Println("status:", res.StatusCode) | |
defer res.Body.Close() | |
body, err := ioutil.ReadAll(res.Body) | |
if err != nil { | |
errorProcess(err) | |
} | |
err = json.Unmarshal(body, &data) | |
if err != nil { | |
errorProcess(err) | |
} | |
pp.Println(data) | |
} else { | |
var reqData map[string]interface{} | |
var resData map[string]interface{} | |
reqBytes := []byte(postData) | |
err := json.Unmarshal(reqBytes, &reqData) | |
pp.Println("========== req ==========") | |
pp.Println(reqData) | |
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBytes)) | |
req.Header.Add("Content-Type", "application/json; charset=utf-8") | |
res, err := client.Do(req) | |
if err != nil { | |
errorProcess(err) | |
} | |
pp.Println("========== res ==========") | |
pp.Println("status:", res.StatusCode) | |
defer res.Body.Close() | |
body, err := ioutil.ReadAll(res.Body) | |
if err != nil { | |
errorProcess(err) | |
} | |
err = json.Unmarshal(body, &resData) | |
if err != nil { | |
errorProcess(err) | |
} | |
pp.Println(resData) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment