Lesson2 Go语言的实战案例|青训营笔记

48 阅读2分钟

1.4 简易Demo上手

1.4.1 猜数字游戏

通过rand.Seed设置随机数种子,生成100以内的随机数,通过bufio和reader读取输入的字符串,通过atoi函数转换为数值,然后进行判断,比较简单。

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(secretNumber)
​
  fmt.Println("请输入你猜的数字:")
  reader := bufio.NewReader(os.Stdin) // 输入for {
    input, err := reader.ReadString('\n')
​
    if err != nil {
      fmt.Println("输入出现错误,请重试", err)
      return
    }
    input = strings.TrimSuffix(input, "\n") // 去除换行符
​
    guess, err := strconv.Atoi(input) // 字符串转数字
    if err != nil {
      fmt.Println("转换出现错误,请重试", err)
      return
    }
​
    if guess > secretNumber {
      fmt.Println("大了")
    } else if guess < secretNumber {
      fmt.Println("小了")
    } else {
      fmt.Println("正确")
      break
    }
    fmt.Println("你猜测的数字是", guess)
  }
}

1.4.2 在线词典

通过游览器抓取API,先Copy as cURL,然后打开 curlconverter.com/ ,将内容粘贴进去,就会自动生成请求代码(与Postman类似)。通过 oktools.net/json2go 生成response的结构体。

代码示例(由于接口变化可能会失效,需要重新抓请求头和响应体):

package main
​
import (
  "bytes"
  "encoding/json"
  "fmt"
  "io"
  "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 {
  } `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", "https://api.interpreter.caiyunai.com/v1/dict", data)
  if err != nil {
    log.Fatal(err)
  }
  req.Header.Set("authority", "api.interpreter.caiyunai.com")
  req.Header.Set("accept", "application/json, text/plain, */*")
  req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
  req.Header.Set("app-name", "xy")
  req.Header.Set("content-type", "application/json;charset=UTF-8")
  req.Header.Set("device-id", "5c0f93dfde4138785373007fcda72e8d")
  req.Header.Set("origin", "https://fanyi.caiyunapp.com")
  req.Header.Set("os-type", "web")
  req.Header.Set("referer", "https://fanyi.caiyunapp.com/")
  req.Header.Set("sec-ch-ua", `"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"`)
  req.Header.Set("sec-ch-ua-mobile", "?0")
  req.Header.Set("sec-ch-ua-platform", `"macOS"`)
  req.Header.Set("sec-fetch-dest", "empty")
  req.Header.Set("sec-fetch-mode", "cors")
  req.Header.Set("sec-fetch-site", "cross-site")
  req.Header.Set("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36")
  req.Header.Set("x-authorization", "token:qgemv4jr1y38jyq6vhvi")
  resp, err := client.Do(req)
  if err != nil {
    log.Fatal(err)
  }
  defer resp.Body.Close()
  bodyText, err := io.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)
}

运行结果:

(base) ➜  go run dict.go nice   
nice UK: [nais] US: [naɪs]
a.好的;令人愉快的;精细的;狡黠的;规矩的;讲究的;文雅的;谨慎的;坏的;放肆的;浪荡的

1.4.3 SOCKS5代理Demo

github.com/wangkechun/…