当前位置:   article > 正文

【go语言】两个翻译引擎来提高响应速度_go io.readall 很慢

go io.readall 很慢

目录

一、直接调用两个翻译函数

        1.完整代码

2.运行时间

二、并行后

         1.完整代码

2.运行时间


一、直接调用两个翻译函数

1.完整代码

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. // "strings"
  10. "os"
  11. "time"
  12. )
  13. type DictResponse struct {
  14. Words []struct {
  15. Source int `json:"source"`
  16. Text string `json:"text"`
  17. PosList []struct {
  18. Type int `json:"type"`
  19. Phonetics []struct {
  20. Type int `json:"type"`
  21. Text string `json:"text"`
  22. } `json:"phonetics"`
  23. Explanations []struct {
  24. Text string `json:"text"`
  25. Examples []struct {
  26. Type int `json:"type"`
  27. Sentences []struct {
  28. Text string `json:"text"`
  29. TransText string `json:"trans_text"`
  30. } `json:"sentences"`
  31. } `json:"examples"`
  32. Synonyms []interface{} `json:"synonyms"`
  33. } `json:"explanations"`
  34. Relevancys []interface{} `json:"relevancys"`
  35. } `json:"pos_list"`
  36. } `json:"words"`
  37. Phrases []interface{} `json:"phrases"`
  38. BaseResp struct {
  39. StatusCode int `json:"status_code"`
  40. StatusMessage string `json:"status_message"`
  41. } `json:"base_resp"`
  42. }
  43. type DictRequest struct {
  44. Text string `json:"text"`
  45. Language string `json:"language"`
  46. }
  47. type DictResponse2 struct {
  48. Rc int `json:"rc"`
  49. Wiki struct {
  50. KnownInLaguages int `json:"known_in_laguages"`
  51. Description struct {
  52. Source string `json:"source"`
  53. Target interface{} `json:"target"`
  54. } `json:"description"`
  55. ID string `json:"id"`
  56. Item struct {
  57. Source string `json:"source"`
  58. Target string `json:"target"`
  59. } `json:"item"`
  60. ImageURL string `json:"image_url"`
  61. IsSubject string `json:"is_subject"`
  62. Sitelink string `json:"sitelink"`
  63. } `json:"wiki"`
  64. Dictionary struct {
  65. Prons struct {
  66. EnUs string `json:"en-us"`
  67. En string `json:"en"`
  68. } `json:"prons"`
  69. Explanations []string `json:"explanations"`
  70. Synonym []string `json:"synonym"`
  71. Antonym []string `json:"antonym"`
  72. WqxExample [][]string `json:"wqx_example"`
  73. Entry string `json:"entry"`
  74. Type string `json:"type"`
  75. Related []interface{} `json:"related"`
  76. Source string `json:"source"`
  77. } `json:"dictionary"`
  78. }
  79. type DictRequest2 struct {
  80. TransType string `json:"trans_type"`
  81. Source string `json:"source"`
  82. UserID string `json:"user_id"`
  83. }
  84. func query2(word string) {
  85. client := &http.Client{}
  86. request := DictRequest2{TransType: "en2zh", Source: word}
  87. buf, err := json.Marshal(request)
  88. if err != nil {
  89. log.Fatal(err)
  90. }
  91. var data = bytes.NewReader(buf)
  92. req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
  93. if err != nil {
  94. log.Fatal(err)
  95. }
  96. req.Header.Set("Connection", "keep-alive")
  97. req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="8"`)
  98. req.Header.Set("sec-ch-ua-mobile", "?0")
  99. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.4153 SLBChan/30")
  100. req.Header.Set("app-name", "xy")
  101. req.Header.Set("Content-Type", "application/json;charset=UTF-8")
  102. req.Header.Set("Accept", "application/json, text/plain, */*")
  103. req.Header.Set("os-type", "web")
  104. req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
  105. req.Header.Set("Origin", "https://fanyi.caiyunapp.com")
  106. req.Header.Set("Sec-Fetch-Site", "cross-site")
  107. req.Header.Set("Sec-Fetch-Mode", "cors")
  108. req.Header.Set("Sec-Fetch-Dest", "empty")
  109. req.Header.Set("Referer", "https://fanyi.caiyunapp.com/")
  110. req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
  111. resp, err := client.Do(req)
  112. if err != nil {
  113. log.Fatal(err)
  114. }
  115. defer resp.Body.Close()
  116. bodyText, err := ioutil.ReadAll(resp.Body)
  117. if err != nil {
  118. log.Fatal(err)
  119. }
  120. if resp.StatusCode != 200 {
  121. log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
  122. }
  123. var dictResponse2 DictResponse2
  124. err = json.Unmarshal(bodyText, &dictResponse2)
  125. if err != nil {
  126. log.Fatal(err)
  127. }
  128. fmt.Println("----------彩云翻译----------")
  129. fmt.Println(word, "UK:", dictResponse2.Dictionary.Prons.En, "US", dictResponse2.Dictionary.Prons.EnUs)
  130. for _, item := range dictResponse2.Dictionary.Explanations {
  131. fmt.Println(item)
  132. }
  133. fmt.Println("")
  134. }
  135. func query(word string) {
  136. client := &http.Client{}
  137. request := DictRequest{Text: word, Language: "en"}
  138. buf, err := json.Marshal(request)
  139. if err != nil {
  140. log.Fatal(err)
  141. }
  142. var data = bytes.NewReader(buf)
  143. req, err := http.NewRequest("POST", "https://translate.volcengine.com/web/dict/match/v1/?msToken=&X-Bogus=DFSzswVLQDcCwINsSW/NZM9WX7jy&_signature=_02B4Z6wo000015fhpVAAAIDDF-NfE7sRI6-X4aHAAIeXgfG9te8myjutgShQB8jqUDatCy40MOwV-0bqoPUXu9GDqeo.aQKg0Wf1bxIiw8tkAhWWJy3ifEthBdCgN69zoNwnBh2B5hsm-2NKb1", data)
  144. if err != nil {
  145. log.Fatal(err)
  146. }
  147. req.Header.Set("authority", "translate.volcengine.com")
  148. req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="8"`)
  149. req.Header.Set("accept", "application/json, text/plain, */*")
  150. req.Header.Set("sec-ch-ua-mobile", "?0")
  151. req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.4153 SLBChan/30")
  152. req.Header.Set("content-type", "application/json")
  153. req.Header.Set("origin", "https://translate.volcengine.com")
  154. req.Header.Set("sec-fetch-site", "same-origin")
  155. req.Header.Set("sec-fetch-mode", "cors")
  156. req.Header.Set("sec-fetch-dest", "empty")
  157. req.Header.Set("referer", "https://translate.volcengine.com/translate?category=&home_language=zh&source_language=en&target_language=zh&text=hello")
  158. req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
  159. req.Header.Set("cookie", "x-jupiter-uuid=16519923780453448; i18next=zh-CN; s_v_web_id=verify_1eac8644bba5cc2fca342fbda9d310d2; _tea_utm_cache_2018=undefined; ttcid=0622e7c8207f4922b25f1e677099901633; tt_scid=NKQPTZgJZyxBCL8qyT-pnS71RE74xJ3XV-FO8r7QN04uJ2kj8Q240-UNUSPeo1VN1aff")
  160. resp, err := client.Do(req)
  161. if err != nil {
  162. log.Fatal(err)
  163. }
  164. defer resp.Body.Close()
  165. bodyText, err := ioutil.ReadAll(resp.Body)
  166. if err != nil {
  167. log.Fatal(err)
  168. }
  169. if resp.StatusCode != 200 {
  170. log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
  171. }
  172. var dictResponse DictResponse
  173. err = json.Unmarshal(bodyText, &dictResponse)
  174. if err != nil {
  175. log.Fatal(err)
  176. }
  177. fmt.Println("----------火山翻译----------")
  178. fmt.Println(word, "UK:", dictResponse.Words[0].PosList[0].Phonetics[0].Text, "US:", dictResponse.Words[0].PosList[0].Phonetics[1].Text)
  179. for _, word := range dictResponse.Words {
  180. for _, posList := range word.PosList {
  181. for _, explanations := range posList.Explanations {
  182. fmt.Printf(explanations.Text)
  183. }
  184. }
  185. }
  186. fmt.Println("")
  187. }
  188. func main() {
  189. start := time.Now()
  190. if len(os.Args) != 2 {
  191. fmt.Fprintln(os.Stderr, `usage: simpleDict WORD
  192. example: simpleDict hello
  193. `)
  194. os.Exit(1)
  195. }
  196. word := os.Args[1]
  197. // wg := sync.WaitGroup{}
  198. query(word)
  199. query2(word)
  200. finish := time.Now()
  201. fmt.Println("run time:", finish.Sub(start))
  202. }

2.运行时间

二、并行后

 1.完整代码

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "sync"
  10. // "strings"
  11. "os"
  12. "time"
  13. )
  14. type DictResponse struct {
  15. Words []struct {
  16. Source int `json:"source"`
  17. Text string `json:"text"`
  18. PosList []struct {
  19. Type int `json:"type"`
  20. Phonetics []struct {
  21. Type int `json:"type"`
  22. Text string `json:"text"`
  23. } `json:"phonetics"`
  24. Explanations []struct {
  25. Text string `json:"text"`
  26. Examples []struct {
  27. Type int `json:"type"`
  28. Sentences []struct {
  29. Text string `json:"text"`
  30. TransText string `json:"trans_text"`
  31. } `json:"sentences"`
  32. } `json:"examples"`
  33. Synonyms []interface{} `json:"synonyms"`
  34. } `json:"explanations"`
  35. Relevancys []interface{} `json:"relevancys"`
  36. } `json:"pos_list"`
  37. } `json:"words"`
  38. Phrases []interface{} `json:"phrases"`
  39. BaseResp struct {
  40. StatusCode int `json:"status_code"`
  41. StatusMessage string `json:"status_message"`
  42. } `json:"base_resp"`
  43. }
  44. type DictRequest struct {
  45. Text string `json:"text"`
  46. Language string `json:"language"`
  47. }
  48. type DictResponse2 struct {
  49. Rc int `json:"rc"`
  50. Wiki struct {
  51. KnownInLaguages int `json:"known_in_laguages"`
  52. Description struct {
  53. Source string `json:"source"`
  54. Target interface{} `json:"target"`
  55. } `json:"description"`
  56. ID string `json:"id"`
  57. Item struct {
  58. Source string `json:"source"`
  59. Target string `json:"target"`
  60. } `json:"item"`
  61. ImageURL string `json:"image_url"`
  62. IsSubject string `json:"is_subject"`
  63. Sitelink string `json:"sitelink"`
  64. } `json:"wiki"`
  65. Dictionary struct {
  66. Prons struct {
  67. EnUs string `json:"en-us"`
  68. En string `json:"en"`
  69. } `json:"prons"`
  70. Explanations []string `json:"explanations"`
  71. Synonym []string `json:"synonym"`
  72. Antonym []string `json:"antonym"`
  73. WqxExample [][]string `json:"wqx_example"`
  74. Entry string `json:"entry"`
  75. Type string `json:"type"`
  76. Related []interface{} `json:"related"`
  77. Source string `json:"source"`
  78. } `json:"dictionary"`
  79. }
  80. type DictRequest2 struct {
  81. TransType string `json:"trans_type"`
  82. Source string `json:"source"`
  83. UserID string `json:"user_id"`
  84. }
  85. func query2(word string,wg *sync.WaitGroup) {
  86. client := &http.Client{}
  87. request := DictRequest2{TransType: "en2zh", Source: word}
  88. defer wg.Done()
  89. buf, err := json.Marshal(request)
  90. if err != nil {
  91. log.Fatal(err)
  92. }
  93. var data = bytes.NewReader(buf)
  94. req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
  95. if err != nil {
  96. log.Fatal(err)
  97. }
  98. req.Header.Set("Connection", "keep-alive")
  99. req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="8"`)
  100. req.Header.Set("sec-ch-ua-mobile", "?0")
  101. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.4153 SLBChan/30")
  102. req.Header.Set("app-name", "xy")
  103. req.Header.Set("Content-Type", "application/json;charset=UTF-8")
  104. req.Header.Set("Accept", "application/json, text/plain, */*")
  105. req.Header.Set("os-type", "web")
  106. req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
  107. req.Header.Set("Origin", "https://fanyi.caiyunapp.com")
  108. req.Header.Set("Sec-Fetch-Site", "cross-site")
  109. req.Header.Set("Sec-Fetch-Mode", "cors")
  110. req.Header.Set("Sec-Fetch-Dest", "empty")
  111. req.Header.Set("Referer", "https://fanyi.caiyunapp.com/")
  112. req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
  113. resp, err := client.Do(req)
  114. if err != nil {
  115. log.Fatal(err)
  116. }
  117. defer resp.Body.Close()
  118. bodyText, err := ioutil.ReadAll(resp.Body)
  119. if err != nil {
  120. log.Fatal(err)
  121. }
  122. if resp.StatusCode != 200 {
  123. log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
  124. }
  125. var dictResponse2 DictResponse2
  126. err = json.Unmarshal(bodyText, &dictResponse2)
  127. if err != nil {
  128. log.Fatal(err)
  129. }
  130. fmt.Println("----------彩云翻译----------")
  131. fmt.Println(word, "UK:", dictResponse2.Dictionary.Prons.En, "US", dictResponse2.Dictionary.Prons.EnUs)
  132. for _, item := range dictResponse2.Dictionary.Explanations {
  133. fmt.Println(item)
  134. }
  135. fmt.Println("")
  136. }
  137. func query(word string,wg *sync.WaitGroup) {
  138. client := &http.Client{}
  139. request := DictRequest{Text: word, Language: "en"}
  140. defer wg.Done()
  141. buf, err := json.Marshal(request)
  142. if err != nil {
  143. log.Fatal(err)
  144. }
  145. var data = bytes.NewReader(buf)
  146. req, err := http.NewRequest("POST", "https://translate.volcengine.com/web/dict/match/v1/?msToken=&X-Bogus=DFSzswVLQDcCwINsSW/NZM9WX7jy&_signature=_02B4Z6wo000015fhpVAAAIDDF-NfE7sRI6-X4aHAAIeXgfG9te8myjutgShQB8jqUDatCy40MOwV-0bqoPUXu9GDqeo.aQKg0Wf1bxIiw8tkAhWWJy3ifEthBdCgN69zoNwnBh2B5hsm-2NKb1", data)
  147. if err != nil {
  148. log.Fatal(err)
  149. }
  150. req.Header.Set("authority", "translate.volcengine.com")
  151. req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="8"`)
  152. req.Header.Set("accept", "application/json, text/plain, */*")
  153. req.Header.Set("sec-ch-ua-mobile", "?0")
  154. req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.4153 SLBChan/30")
  155. req.Header.Set("content-type", "application/json")
  156. req.Header.Set("origin", "https://translate.volcengine.com")
  157. req.Header.Set("sec-fetch-site", "same-origin")
  158. req.Header.Set("sec-fetch-mode", "cors")
  159. req.Header.Set("sec-fetch-dest", "empty")
  160. req.Header.Set("referer", "https://translate.volcengine.com/translate?category=&home_language=zh&source_language=en&target_language=zh&text=hello")
  161. req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
  162. req.Header.Set("cookie", "x-jupiter-uuid=16519923780453448; i18next=zh-CN; s_v_web_id=verify_1eac8644bba5cc2fca342fbda9d310d2; _tea_utm_cache_2018=undefined; ttcid=0622e7c8207f4922b25f1e677099901633; tt_scid=NKQPTZgJZyxBCL8qyT-pnS71RE74xJ3XV-FO8r7QN04uJ2kj8Q240-UNUSPeo1VN1aff")
  163. resp, err := client.Do(req)
  164. if err != nil {
  165. log.Fatal(err)
  166. }
  167. defer resp.Body.Close()
  168. bodyText, err := ioutil.ReadAll(resp.Body)
  169. if err != nil {
  170. log.Fatal(err)
  171. }
  172. if resp.StatusCode != 200 {
  173. log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
  174. }
  175. var dictResponse DictResponse
  176. err = json.Unmarshal(bodyText, &dictResponse)
  177. if err != nil {
  178. log.Fatal(err)
  179. }
  180. fmt.Println("----------火山翻译----------")
  181. fmt.Println(word, "UK:", dictResponse.Words[0].PosList[0].Phonetics[0].Text, "US:", dictResponse.Words[0].PosList[0].Phonetics[1].Text)
  182. for _, word := range dictResponse.Words {
  183. for _, posList := range word.PosList {
  184. for _, explanations := range posList.Explanations {
  185. fmt.Printf(explanations.Text)
  186. }
  187. }
  188. }
  189. fmt.Println("")
  190. }
  191. func main() {
  192. start := time.Now()
  193. if len(os.Args) != 2 {
  194. fmt.Fprintln(os.Stderr, `usage: simpleDict WORD
  195. example: simpleDict hello
  196. `)
  197. os.Exit(1)
  198. }
  199. word := os.Args[1]
  200. var wg sync.WaitGroup
  201. // wg := sync.WaitGroup{}
  202. wg.Add(2)
  203. go query(word, &wg)
  204. go query2(word, &wg)
  205. wg.Wait()
  206. finish := time.Now()
  207. fmt.Println("run time:",finish.Sub(start))
  208. }

2.运行时间

 

 明显并行后的运行时间更快

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/372213
推荐阅读
相关标签
  

闽ICP备14008679号