【go语言】在线小词典

目录

一、以火山翻译为例子

        1.完整代码

       2.运行结果

 二、以彩云翻译为例

        1.完整代码

        2.运行结果

三、用到的工具


一、以火山翻译为例子

        1.完整代码

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	// "strings"
	"os"
)

type DictResponse struct {
	Words []struct {
		Source int `json:"source"`
		Text string `json:"text"`
		PosList []struct {
			Type int `json:"type"`
			Phonetics []struct {
				Type int `json:"type"`
				Text string `json:"text"`
			} `json:"phonetics"`
			Explanations []struct {
				Text string `json:"text"`
				Examples []struct {
					Type int `json:"type"`
					Sentences []struct {
						Text string `json:"text"`
						TransText string `json:"trans_text"`
					} `json:"sentences"`
				} `json:"examples"`
				Synonyms []interface{} `json:"synonyms"`
			} `json:"explanations"`
			Relevancys []interface{} `json:"relevancys"`
		} `json:"pos_list"`
	} `json:"words"`
	Phrases []interface{} `json:"phrases"`
	BaseResp struct {
		StatusCode int `json:"status_code"`
		StatusMessage string `json:"status_message"`
	} `json:"base_resp"`
}

type DictRequest struct {
	Text string `json:"text"`
	Language string `json:"language"`
}
func query(word string){
	client := &http.Client{}
	// var data = strings.NewReader(`{"text":"hello","language":"en"}`)
	request := DictRequest{Text: word, Language: "en"}
	buf, err := json.Marshal(request)
	if err != nil {
		log.Fatal(err)
	}
	var data = bytes.NewReader(buf)
	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)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("authority", "translate.volcengine.com")
	req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="8"`)
	req.Header.Set("accept", "application/json, text/plain, */*")
	req.Header.Set("sec-ch-ua-mobile", "?0")
	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")
	req.Header.Set("content-type", "application/json")
	req.Header.Set("origin", "https://translate.volcengine.com")
	req.Header.Set("sec-fetch-site", "same-origin")
	req.Header.Set("sec-fetch-mode", "cors")
	req.Header.Set("sec-fetch-dest", "empty")
	req.Header.Set("referer", "https://translate.volcengine.com/translate?category=&home_language=zh&source_language=en&target_language=zh&text=hello")
	req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
	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")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	bodyText, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	if resp.StatusCode != 200 {
		log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
}
	// fmt.Printf("%s\n", bodyText)
	var dictResponse DictResponse
	err = json.Unmarshal(bodyText, &dictResponse)
	if err != nil {
		log.Fatal(err)
	}
	// fmt.Printf("%#v\n",dictResponse)
	fmt.Println(word,"UK:", dictResponse.Words[0].PosList[0].Phonetics[0].Text,"US:",dictResponse.Words[0].PosList[0].Phonetics[1].Text)
	for _,word := range dictResponse.Words {
		for _, posList := range word.PosList {
				for _, explanations := range posList.Explanations {
					fmt.Printf(explanations.Text)
				}
		}
	}
	fmt.Println("")
	// for _, item := range dictResponse.Words[0].PosList[0].Explanations {
	// 		fmt.Println(item)
	// }
}
func main(){
	if len(os.Args) != 2 {
			fmt.Fprintln(os.Stderr,`usage: simpleDict WORD
		example: simpleDict hello
			`)
			os.Exit(1)
	}
	word := os.Args[1]
	query(word)
}

       2.运行结果

 二、以彩云翻译为例

        1.完整代码

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	//"strings"
)
type  DictResponse2 struct {
	Rc int `json:"rc"`
	Wiki struct {
		KnownInLaguages int `json:"known_in_laguages"`
		Description struct {
			Source string `json:"source"`
			Target interface{} `json:"target"`
		} `json:"description"`
		ID string `json:"id"`
		Item struct {
			Source string `json:"source"`
			Target string `json:"target"`
		} `json:"item"`
		ImageURL string `json:"image_url"`
		IsSubject string `json:"is_subject"`
		Sitelink string `json:"sitelink"`
	} `json:"wiki"`
	Dictionary struct {
		Prons struct {
			EnUs string `json:"en-us"`
			En string `json:"en"`
		} `json:"prons"`
		Explanations []string `json:"explanations"`
		Synonym []string `json:"synonym"`
		Antonym []string `json:"antonym"`
		WqxExample [][]string `json:"wqx_example"`
		Entry string `json:"entry"`
		Type string `json:"type"`
		Related []interface{} `json:"related"`
		Source string `json:"source"`
	} `json:"dictionary"`
}

type DictRequest2 struct {
		TransType string `json:"trans_type"`
		Source		string `json:"source"`
		UserID		string `json:"user_id"`
}

//func main() {
	func query(word string){
			client := &http.Client{}
			//var data = strings.NewReader(`{"trans_type":"en2zh","source":"good"}`)
			//request := DictRequest{TransType: "en2zh", Source: "good"}
			request := DictRequest2{TransType: "en2zh", Source: word}
			buf, err := json.Marshal(request)
			if err != nil {
				log.Fatal(err)
			}
			var data = bytes.NewReader(buf)
			req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
			if err != nil {
				log.Fatal(err)
			}
			req.Header.Set("Connection", "keep-alive")
			req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="8"`)
			req.Header.Set("sec-ch-ua-mobile", "?0")
			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")
			req.Header.Set("app-name", "xy")
			req.Header.Set("Content-Type", "application/json;charset=UTF-8")
			req.Header.Set("Accept", "application/json, text/plain, */*")
			req.Header.Set("os-type", "web")
			req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
			req.Header.Set("Origin", "https://fanyi.caiyunapp.com")
			req.Header.Set("Sec-Fetch-Site", "cross-site")
			req.Header.Set("Sec-Fetch-Mode", "cors")
			req.Header.Set("Sec-Fetch-Dest", "empty")
			req.Header.Set("Referer", "https://fanyi.caiyunapp.com/")
			req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
			resp, err := client.Do(req)
			if err != nil {
				log.Fatal(err)
			}
			defer resp.Body.Close()
			bodyText, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				log.Fatal(err)
			}
			if resp.StatusCode != 200 {
					log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
			}
			//fmt.Printf("%s\n", bodyText)
			var dictResponse2 DictResponse2
			err = json.Unmarshal(bodyText, &dictResponse2)
			if err != nil {
				log.Fatal(err)
			}
			//fmt.Printf("%#v\n",dictResponse)
			fmt.Println(word,"UK:", dictResponse2.Dictionary.Prons.En, "US", dictResponse2.Dictionary.Prons.EnUs)
			for _, item := range dictResponse2.Dictionary.Explanations {
					fmt.Println(item)
			}
}
func main(){
	if len(os.Args) != 2 {
			fmt.Fprintln(os.Stderr,`usage: simpleDict WORD
		example: simpleDict hello
			`)
			os.Exit(1)
	}
	word := os.Args[1]
	query(word)
}

        2.运行结果

 

三、用到的工具

进行一些格式转换的网站,比如json转go strust

Jj​​​​​​​https://oktools.net/json2go

【go语言】在线小词典_第1张图片 

curl转换器网站

https://curlconverter.com/#go 

【go语言】在线小词典_第2张图片 

 

 

你可能感兴趣的:(go语言,golang,开发语言,后端,经验分享)