github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/ws/wsmessagequery.go (about) 1 package ws 2 3 import ( 4 "encoding/json" 5 "io" 6 "net/http" 7 "net/url" 8 9 "github.com/pkg/errors" 10 "github.com/spf13/cobra" 11 12 "github.com/iotexproject/iotex-core/ioctl/config" 13 "github.com/iotexproject/iotex-core/ioctl/output" 14 ) 15 16 var ( 17 // wsMessageQuery represents the w3bstream query message command 18 wsMessageQuery = &cobra.Command{ 19 Use: "query", 20 Short: config.TranslateInLang(wsMessageQueryShorts, config.UILanguage), 21 RunE: func(cmd *cobra.Command, args []string) error { 22 id, err := cmd.Flags().GetString("message-id") 23 if err != nil { 24 return errors.Wrap(err, "failed to get flag message-id") 25 } 26 tok, err := cmd.Flags().GetString("did-vc-token") 27 if err != nil { 28 return errors.Wrap(err, "failed to get flag did-vc-token") 29 } 30 31 out, err := queryMessageStatus(id, tok) 32 if err != nil { 33 return output.PrintError(err) 34 } 35 output.PrintResult(out) 36 return nil 37 }, 38 } 39 40 // wsMessageSendShorts w3bstream message query shorts multi-lang support 41 wsMessageQueryShorts = map[config.Language]string{ 42 config.English: "query message status from w3bstream", 43 config.Chinese: "向w3bstream查询消息状态", 44 } 45 46 _flagMessageIDUsages = map[config.Language]string{ 47 config.English: "message id", 48 config.Chinese: "消息ID", 49 } 50 ) 51 52 func init() { 53 wsMessageQuery.Flags().StringP("message-id", "i", "", config.TranslateInLang(_flagMessageIDUsages, config.UILanguage)) 54 wsMessageQuery.Flags().StringP("did-vc-token", "t", "", config.TranslateInLang(_flagDIDVCTokenUsages, config.UILanguage)) 55 56 _ = wsMessageQuery.MarkFlagRequired("message-id") 57 } 58 59 func queryMessageStatus(id string, tok string) (string, error) { 60 u := url.URL{ 61 Scheme: "http", 62 Host: config.ReadConfig.WsEndpoint, 63 Path: "/message/" + id, 64 } 65 66 req, err := http.NewRequest(http.MethodGet, u.String(), nil) 67 if err != nil { 68 return "", errors.Wrap(err, "failed to new http request") 69 } 70 71 if tok != "" { 72 req.Header.Set("Authorization", tok) 73 } 74 75 rsp, err := http.DefaultClient.Do(req) 76 if err != nil { 77 return "", errors.Wrap(err, "call w3bstream failed") 78 } 79 defer rsp.Body.Close() 80 81 switch sc := rsp.StatusCode; sc { 82 case http.StatusNotFound: 83 return "", errors.Errorf("the message [%s] is not found or expired", id) 84 case http.StatusOK: 85 default: 86 return "", errors.Errorf("responded status code: %d", sc) 87 } 88 89 rspbody, err := io.ReadAll(rsp.Body) 90 if err != nil { 91 return "", errors.Wrap(err, "read responded body failed") 92 } 93 94 rspdata := &queryMessageRsp{} 95 if err = json.Unmarshal(rspbody, rspdata); err != nil { 96 return "", errors.Wrap(err, "parse responded body failed") 97 } 98 out, err := json.MarshalIndent(rspdata, "", " ") 99 return string(out), err 100 }