这是我参与「第三届青训营 -后端场」笔记创作活动的的第1篇笔记
简单记录一下,没排版
1.实际业务逻辑函数一般返回两个值,第一个是真正的返回值,第二个是错误信息
2.go语言错误处理
if err != nil{
//do something
}
当出现不等于nil时,说明出现了一些错误
3.格式化输出%v简单输出,%+v更详细输出
4.当我们从键盘输入回车键时,Windows系统会把回车键当做\r\n 来处理,而Linux系统只会当做\n 来处理
curl转换小工具:curlconverter.com/#go
错误处理很重要!实际工业逻辑中这个很重要!
作业1: 简单改为scanf即可,很简单
作业2:常用的有道词典
注意是trans项不是dict项
运用课堂上的两个小工具转化即可
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
type DictResponse struct {
ReturnPhrase []string `json:"returnPhrase"`
Query string `json:"query"`
ErrorCode string `json:"errorCode"`
L string `json:"l"`
TSpeakURL string `json:"tSpeakUrl"`
Web []struct {
Value []string `json:"value"`
Key string `json:"key"`
} `json:"web"`
RequestID string `json:"requestId"`
Translation []string `json:"translation"`
Dict struct {
URL string `json:"url"`
} `json:"dict"`
Webdict struct {
URL string `json:"url"`
} `json:"webdict"`
Basic struct {
ExamType []string `json:"exam_type"`
UsPhonetic string `json:"us-phonetic"`
Phonetic string `json:"phonetic"`
UkPhonetic string `json:"uk-phonetic"`
Wfs []struct {
Wf struct {
Name string `json:"name"`
Value string `json:"value"`
} `json:"wf"`
} `json:"wfs"`
UkSpeech string `json:"uk-speech"`
Explains []string `json:"explains"`
UsSpeech string `json:"us-speech"`
} `json:"basic"`
IsWord bool `json:"isWord"`
SpeakURL string `json:"speakUrl"`
}
func query(word string) {
client := &http.Client{}
var data = strings.NewReader(`q=hello&from=Auto&to=Auto`)
req, err := http.NewRequest("POST", "https://aidemo.youdao.com/trans", data)
if err != nil {
log.Fatal(err)
}
req.Header.Set("authority", "aidemo.youdao.com")
req.Header.Set("accept", "application/json, text/javascript, */*; q=0.01")
req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
req.Header.Set("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("origin", "https://ai.youdao.com")
req.Header.Set("referer", "https://ai.youdao.com/")
req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"`)
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("sec-ch-ua-platform", `"Windows"`)
req.Header.Set("sec-fetch-dest", "empty")
req.Header.Set("sec-fetch-mode", "cors")
req.Header.Set("sec-fetch-site", "same-site")
req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36")
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))
}
var dictResponse DictResponse
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err)
}
fmt.Println(word)
for _, item := range dictResponse.Basic.Explains {
fmt.Println(item)
}
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, `usage: simpleDict WORD
example: simpleDict hello
`)
os.Exit(1)
}
word := os.Args[1]
query(word)
}
作业3: 随手搞了一个,不算真正的并发,不能实现那个快先选哪个的功能
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"sync"
)
type DictRequest struct {
TransType string `json:"trans_type"`
Source string `json:"source"`
UserID string `json:"user_id"`
}
type DictResponse1 struct {
ReturnPhrase []string `json:"returnPhrase"`
Query string `json:"query"`
ErrorCode string `json:"errorCode"`
L string `json:"l"`
TSpeakURL string `json:"tSpeakUrl"`
Web []struct {
Value []string `json:"value"`
Key string `json:"key"`
} `json:"web"`
RequestID string `json:"requestId"`
Translation []string `json:"translation"`
Dict struct {
URL string `json:"url"`
} `json:"dict"`
Webdict struct {
URL string `json:"url"`
} `json:"webdict"`
Basic struct {
ExamType []string `json:"exam_type"`
UsPhonetic string `json:"us-phonetic"`
Phonetic string `json:"phonetic"`
UkPhonetic string `json:"uk-phonetic"`
Wfs []struct {
Wf struct {
Name string `json:"name"`
Value string `json:"value"`
} `json:"wf"`
} `json:"wfs"`
UkSpeech string `json:"uk-speech"`
Explains []string `json:"explains"`
UsSpeech string `json:"us-speech"`
} `json:"basic"`
IsWord bool `json:"isWord"`
SpeakURL string `json:"speakUrl"`
}
type DictResponse 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"`
}
func query(word string) {
fmt.Println("query with caiyun")
client := &http.Client{}
request := DictRequest{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("DNT", "1")
req.Header.Set("os-version", "")
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")
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("device-id", "")
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")
req.Header.Set("Cookie", "_ym_uid=16456948721020430059; _ym_d=1645694872")
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))
}
var dictResponse DictResponse
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err)
}
fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
for _, item := range dictResponse.Dictionary.Explanations {
fmt.Println(item)
}
}
func query1(word string) {
fmt.Println("query with youdao")
client := &http.Client{}
var data = strings.NewReader(`q=hello&from=Auto&to=Auto`)
req, err := http.NewRequest("POST", "https://aidemo.youdao.com/trans", data)
if err != nil {
log.Fatal(err)
}
req.Header.Set("authority", "aidemo.youdao.com")
req.Header.Set("accept", "application/json, text/javascript, */*; q=0.01")
req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
req.Header.Set("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("origin", "https://ai.youdao.com")
req.Header.Set("referer", "https://ai.youdao.com/")
req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"`)
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("sec-ch-ua-platform", `"Windows"`)
req.Header.Set("sec-fetch-dest", "empty")
req.Header.Set("sec-fetch-mode", "cors")
req.Header.Set("sec-fetch-site", "same-site")
req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36")
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))
}
var dictResponse DictResponse1
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err)
}
fmt.Println(word)
for _, item := range dictResponse.Basic.Explains {
fmt.Println(item)
}
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, `usage: simpleDict WORD
example: simpleDict hello
`)
os.Exit(1)
}
word := os.Args[1]
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
query(word)
}()
go func() {
defer wg.Done()
query1(word)
}()
wg.Wait()
}