github.com/zak-blake/goa@v1.4.1/client/cli.go (about) 1 package client 2 3 import ( 4 "bufio" 5 "encoding/json" 6 "fmt" 7 "io/ioutil" 8 "log" 9 "net/http" 10 "os" 11 12 "golang.org/x/net/websocket" 13 ) 14 15 // HandleResponse logs the response details and exits the process with a status computed from 16 // the response status code. The mapping of response status code to exit status is as follows: 17 // 18 // 401: 1 19 // 402 to 500 (other than 403 and 404): 2 20 // 403: 3 21 // 404: 4 22 // 500+: 5 23 func HandleResponse(c *Client, resp *http.Response, pretty bool) { 24 defer resp.Body.Close() 25 body, err := ioutil.ReadAll(resp.Body) 26 if err != nil { 27 fmt.Fprintf(os.Stderr, "failed to read body: %s", err) 28 os.Exit(-1) 29 } 30 if resp.StatusCode < 200 || resp.StatusCode > 299 { 31 // Let user know if something went wrong 32 var sbody string 33 if len(body) > 0 { 34 sbody = ": " + string(body) 35 } 36 fmt.Printf("error: %d%s", resp.StatusCode, sbody) 37 } else if !c.Dump && len(body) > 0 { 38 var out string 39 if pretty { 40 var jbody interface{} 41 err = json.Unmarshal(body, &jbody) 42 if err != nil { 43 out = string(body) 44 } else { 45 var b []byte 46 b, err = json.MarshalIndent(jbody, "", " ") 47 if err == nil { 48 out = string(b) 49 } else { 50 out = string(body) 51 } 52 } 53 } else { 54 out = string(body) 55 } 56 fmt.Print(out) 57 } 58 59 // Figure out exit code 60 exitStatus := 0 61 switch { 62 case resp.StatusCode == 401: 63 exitStatus = 1 64 case resp.StatusCode == 403: 65 exitStatus = 3 66 case resp.StatusCode == 404: 67 exitStatus = 4 68 case resp.StatusCode > 399 && resp.StatusCode < 500: 69 exitStatus = 2 70 case resp.StatusCode > 499: 71 exitStatus = 5 72 } 73 os.Exit(exitStatus) 74 } 75 76 // WSWrite sends STDIN lines to a websocket server. 77 func WSWrite(ws *websocket.Conn) { 78 scanner := bufio.NewScanner(os.Stdin) 79 for scanner.Scan() { 80 t := scanner.Text() 81 ws.Write([]byte(t)) 82 fmt.Printf(">> %s\n", t) 83 } 84 } 85 86 // WSRead reads from a websocket and print the read messages to STDOUT. 87 func WSRead(ws *websocket.Conn) { 88 msg := make([]byte, 512) 89 for { 90 n, err := ws.Read(msg) 91 if err != nil { 92 log.Fatal(err) 93 } 94 fmt.Printf("<< %s\n", msg[:n]) 95 } 96 }