青训营笔记

427 阅读3分钟

掘金课程学习 这是我参加【第五届青训营】伴学笔记创作活动第一天,今天学习了后端入门课程中的Go语言原理与实践,从走进Go语言基础语言开始,了解了Go 是一门高性能,高并发,语法简单,学习曲线平缓的强类型和静态类型语言,其拥有丰富的标准库,完善的工具链,支持快速编译,跨平台且支持垃圾回收;学习了Go语言中的基础语法,如变量,字符串,字符串格式化,数字解析,if else判断,switch,for循环,range,数组,切片,map,函数,指针,结构体,结构体方法,错误处理,defer处理,json处理,时间处理,进程处理,并且可以分辨出与c/c++等相关语言的一些不同。后又进行了Go语言的实战案例和Go语言进阶与依赖管理等后续13个视频的学习。 猜字谜游戏: 设置随机数种子,随机生成100以内的数,提示用户输入,并和用户输入的数据比大小,根据大小提示信息,不断循环,最终猜正确才退出循环。通过该例子巩固变量循环、函数控制流和错误处理等知识 package main

import ( "bufio" "fmt" "math/rand" "os" "strconv" "strings" "time" )

func main() { maxNum := 100 rand.Seed(time.Now().UnixNano()) secretNumber := rand.Intn(maxNum) // fmt.Println("The secret number is ", secretNumber)

fmt.Println("Please input your guess")
reader := bufio.NewReader(os.Stdin)
for {
	input, err := reader.ReadString('\n')
	if err != nil {
		fmt.Println("An error occured while reading input. Please try again", err)
		continue
	}
	input = strings.TrimSuffix(input, "\n")

	guess, err := strconv.Atoi(input)
	if err != nil {
		fmt.Println("Invalid input. Please enter an integer value")
		continue
	}
	fmt.Println("You guess is", guess)
	if guess > secretNumber {
		fmt.Println("Your guess is bigger than the secret number. Please try again")
	} else if guess < secretNumber {
		fmt.Println("Your guess is smaller than the secret number. Please try again")
	} else {
		fmt.Println("Correct, you Legend!")
		break
	}
}



} 
在线字典实战案例: 
抓包彩云小译翻译的api,并拷贝curl命令,通过网站转换成go代码,并拷贝服务端响应的json数据,通过网站生成go结构体,然后解析对应的字段输出,通过该例子学习发送http请求、解析json格式、使用代码生成提高开发效率等

package main

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

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

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) { 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", "[api.interpreter.caiyunai.com/v1/dict](https://api.interpreter.caiyunai.com/v1/dict "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", "[fanyi.caiyunapp.com](https://fanyi.caiyunapp.com/ "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", "[fanyi.caiyunapp.com/](https://fanyi.caiyunapp.com/ "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 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) }