package speechNlu import ( "encoding/json" "fmt" "github.com/gorilla/websocket" "io/ioutil" "net/http" "speech-nlu-parse/global" "speech-nlu-parse/model" "speech-nlu-parse/pkg/logger" "sync" "time" ) type SpeechNlpWs struct { NlpWsConn *websocket.Conn mutex sync.Mutex } func (s *SpeechNlpWs) SpeechWs() (*websocket.Conn, error) { SpeechWs_Url := global.SpeechSetting.Url SpeechWs_ProductId := global.SpeechSetting.ProductId SpeechWs_ApiKey := global.SpeechSetting.ApiKey //st := time.Now() dialer := websocket.Dialer{ HandshakeTimeout: 30 * time.Second, } header := http.Header{} SpeechUrl := SpeechWs_Url + "?serviceType=websocket&productId=" + SpeechWs_ProductId + "&apikey=" + SpeechWs_ApiKey fmt.Println(SpeechUrl) conn, resp, err := dialer.Dial(SpeechUrl, header) if err != nil { global.Logger.WithFields(logger.Fields{ //"RequestId": p.RequestId, "resp": readResp(resp), }).Errorf("[SpeechWs] Connect error : %v", err.Error()) return nil, err } return conn, nil } func (s *SpeechNlpWs) Send(data interface{}) error { s.NlpWsConn.WriteJSON(data) return nil } func (s *SpeechNlpWs) Recv() ([]byte, error) { _, msg, err := s.NlpWsConn.ReadMessage() return msg, err } func readResp(resp *http.Response) string { if resp == nil { return "" } b, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } return fmt.Sprintf("code=%d,body=%s", resp.StatusCode, string(b)) } func SpeechNlpWsReq(data *model.SemanticReq) *SpeechWsData { req := new(SpeechWsData) req.Topic = "nlu.input.text" req.RecordId = data.Guid //sessionId待定 req.RefText = data.Query return req } func (s *SpeechNlpWs) ParseSpeechNluData(jsonData []byte, requestId, sessionId string) []byte { speechNlpWsResp := model.SpeechWsResp{} err := json.Unmarshal(jsonData, &speechNlpWsResp) if err != nil { global.Logger.WithFields(logger.Fields{ "data": map[string]interface{}{"requestBody": string(jsonData)}, "requestId": requestId, }).Error("ParseTNluData Unmarshal error.") return replyWithChat(error_reply, "doudi") } //var jsonByte []byte fmt.Println(jsonData) return jsonData } func (s *SpeechNlpWs) WsSend(body *SpeechWsData) { s.Send(body) } type SpeechWsData struct { Topic string `json:"topic"` // 必选 RecordId string `json:"recordId"` // 可选,uuid,请求标识 SessionId string `json:"sessionId"` // 可选,首轮不带此参数,非首轮必须带此参数 RefText string `json:"refText"` // 必选,请求文本 }