## 实战

#### 项目代码

``````package main

import (
"fmt"
"math/rand"
"time"
)

func main() {
maxNum := 100
rand.Seed(time.Now().UnixNano()) //用时间戳来初始化随机数种子
secretNumber := rand.Intn(maxNum)
//fmt.Println("The secret number is ", secretNumber)

/* 实现用户的输入输出，并解析成数字 */

for {
//if err != nil {
// fmt.Println("An error occured while reading input.Please try again", err)
// //return
// continue
//}
//
//input = strings.TrimSuffix(input, "\n") //去掉换行符
//

var guess int
_, err := fmt.Scanf("%d", &guess)

if err != nil {
fmt.Println("Invaild input. Please enter an integer value")
//return
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
}
}
}

#### 项目二：在线词典

##### 第二步：

``````package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)

func main() {
client := &http.Client{}
var data = strings.NewReader(`{"trans_type":"en2zh","source":"good"}`)
req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36")
req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"`)
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)
}
fmt.Printf("%s\n", bodyText)
}

``````package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)

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

func main() {
client := &http.Client{}
//var data = strings.NewReader(`{"trans_type":"en2zh","source":"good"}`)

//初始化结构体成员
request := DictRequest{TransType: "en2zh", Source: word}
//调用json.Marshal来序列化request变成一个byte数组
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("Accept", "application/json, text/plain, */*")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36")
req.Header.Set("sec-ch-ua", `" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"`)
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)
}
fmt.Printf("%s\n", bodyText)
}

##### 第三步：获取response

``````
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"`
} `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 main() {
//创建一个http实例
client := &http.Client{}
//初始化结构体成员
request := DictRequest{TransType: "en2zh", Source: word}
//调用json.Marshal来序列化request变成一个byte数组
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("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("Accept", "application/json, text/plain, */*")
//发起请求
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
//用Unmarshal将body反序列化到结构体中
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 query(word string) {
//创建一个http实例
client := &http.Client{}
//初始化结构体成员
request := DictRequest{TransType: "en2zh", Source: word}
//调用json.Marshal来序列化request变成一个byte数组
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("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("Accept", "application/json, text/plain, */*")
//发起请求
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
//用Unmarshal将body反序列化到结构体中
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() {
//如果命令和参数的个数不是2
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, `usage: simpleDict WORD
example: simpleDict hello
`)
os.Exit(1)
}
word := os.Args[1]
query(word)
}

#### 项目三 socks5代理

##### 1.建立一个简单的TCP echo server

``````func main() {
//监听一个端口，返回server
server, err := net.Listen("tcp", "127.0.0.1:1080")
if err != nil {
panic(err)
}
for {
//接受一个请求，如果返回成功就会得到一个连接
client, err := server.Accept()
if err != nil {
log.Printf("Accept failed %v", err)
continue
}
//在函数中处理连接，go代表采用goroutine
go process(client)
}
}

func process(conn net.Conn) {
defer conn.Close()
for {
if err != nil {
break
}
_, err = conn.Write([]byte{b})
if err != nil {
break
}
}
}

##### 2.握手-认证阶段

``````func process(conn net.Conn) {
defer conn.Close()
err := auth(reader, conn)
if err != nil {
log.Printf("client %v auth failed:%v", conn.RemoteAddr(), err)
return
}
log.Println("auth success")
}
}

func auth(reader *bufio.Reader, conn net.Conn) (err error) {
// +----+----------+----------+
// |VER | NMETHODS | METHODS  |
// +----+----------+----------+
// | 1  |    1     | 1 to 255 |
// +----+----------+----------+
// VER: 协议版本，socks5为0x05
// NMETHODS: 支持认证的方法数量
// METHODS: 对应NMETHODS，NMETHODS的值为多少，METHODS就有多少个字节。RFC预定义了一些值的含义，内容如下:
// X’00’ NO AUTHENTICATION REQUIRED

//对应VER
if err != nil {
return fmt.Errorf("read ver failed:%w", err)
}
if ver != socks5Ver {
return fmt.Errorf("not supported ver:%v", ver)
}
//对应NMETHNODS
if err != nil {
return fmt.Errorf("read methodSize failed:%w", err)
}
//根据method的大小创建一个缓冲区
method := make([]byte, methodSize)
if err != nil {
return fmt.Errorf("read method failed:%w", err)
}
//log.Println("ver", ver, "method", method) //得到了所有的字段，打印出来
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1  |   1    |
// +----+--------+

//返回一个包，告诉浏览器我们选择了哪种认证方式
_, err = conn.Write([]byte{socks5Ver, 0x00}) //第一个参数是协议版本号，第二个是认证方式
if err != nil {
return fmt.Errorf("write failed:%w", err)
}
return nil
}

##### 3.请求阶段

``````const socks5Ver = 0x05
const cmdBind = 0x01
const atypIPV4 = 0x01
const atypeHOST = 0x03
const atypeIPV6 = 0x04

func main() {
//监听一个端口，返回server
server, err := net.Listen("tcp", "127.0.0.1:1080")
if err != nil {
panic(err)
}
for {
//接受一个请求，如果返回成功就会得到一个连接
client, err := server.Accept()
if err != nil {
log.Printf("Accept failed %v", err)
continue
}
//在函数中处理连接，go代表采用goroutine
go process(client)
}
}

func process(conn net.Conn) {
defer conn.Close()
err := auth(reader, conn)
if err != nil {
log.Printf("client %v auth failed:%v", conn.RemoteAddr(), err)
return
}
err = connect(reader, conn)
if err != nil {
log.Printf("client %v auth failed:%v", conn.RemoteAddr(), err)
return
}
}

func auth(reader *bufio.Reader, conn net.Conn) (err error) {
// +----+----------+----------+
// |VER | NMETHODS | METHODS  |
// +----+----------+----------+
// | 1  |    1     | 1 to 255 |
// +----+----------+----------+
// VER: 协议版本，socks5为0x05
// NMETHODS: 支持认证的方法数量
// METHODS: 对应NMETHODS，NMETHODS的值为多少，METHODS就有多少个字节。RFC预定义了一些值的含义，内容如下:
// X’00’ NO AUTHENTICATION REQUIRED

//对应VER
if err != nil {
return fmt.Errorf("read ver failed:%w", err)
}
if ver != socks5Ver {
return fmt.Errorf("not supported ver:%v", ver)
}
//对应NMETHNODS
if err != nil {
return fmt.Errorf("read methodSize failed:%w", err)
}
//根据method的大小创建一个缓冲区
method := make([]byte, methodSize)
if err != nil {
return fmt.Errorf("read method failed:%w", err)
}
//log.Println("ver", ver, "method", method) //得到了所有的字段，打印出来
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1  |   1    |
// +----+--------+

//返回一个包，告诉浏览器我们选择了哪种认证方式
_, err = conn.Write([]byte{socks5Ver, 0x00}) //第一个参数是协议版本号，第二个是认证方式
if err != nil {
return fmt.Errorf("write failed:%w", err)
}
return nil
}

func connect(reader *bufio.Reader, conn net.Conn) (err error) {
// +----+-----+-------+------+----------+----------+
// |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1  |  1  | X'00' |  1   | Variable |    2     |
// +----+-----+-------+------+----------+----------+
// VER 版本号，socks5的值为0x05
// CMD 0x01表示CONNECT请求
// RSV 保留字段，值为0x00
// DST.PORT 目标端口，固定2个字节

//创建一个缓冲区，读取前四个字段
buf := make([]byte, 4)
if err != nil {
}
ver, cmd, atyp := buf[0], buf[1], buf[3]
if ver != socks5Ver {
return fmt.Errorf("not supported ver:%v", ver)
}
if cmd != cmdBind {
return fmt.Errorf("not supported cmd:%v", ver)
}
switch atyp {
case atypIPV4: //如果是IPV4，则刚好4个字节，用buf读取即可
if err != nil {
return fmt.Errorf("read atyp failed:%w", err)
}
addr = fmt.Sprintf("%d.%d.%d.%d", buf[0], buf[1], buf[2], buf[3])
case atypeHOST: //如果是其他域名，则先读取域名大小，再填充
if err != nil {
return fmt.Errorf("read hostSize failed:%w", err)
}
host := make([]byte, hostSize)
if err != nil {
return fmt.Errorf("read host failed:%w", err)
}
case atypeIPV6:
return errors.New("IPv6: no supported yet")
default:
return errors.New("invalid atyp")
}
//读取最后一个参数，用切片语法将buf裁剪成一个两个字节的缓冲区
if err != nil {
return fmt.Errorf("read port failed:%w", err)
}
//读取端口号
port := binary.BigEndian.Uint16(buf[:2])

//用tcp协议往对应的域名和端口建立连接
dest, err := net.Dial("tcp", fmt.Sprintf("%v:%v", addr, port))
if err != nil {
return fmt.Errorf("dial dst failed:%w", err)
}
defer dest.Close()

// +----+-----+-------+------+----------+----------+
// |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1  |  1  | X'00' |  1   | Variable |    2     |
// +----+-----+-------+------+----------+----------+
// VER socks版本，这里为0x05
// REP Relay field,内容取值如下 X’00’ succeeded
// RSV 保留字段
// ATYPE 地址类型
// BND.PORT 服务绑定的端口DST.PORT

//回包
_, err = conn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
if err != nil {
return fmt.Errorf("write failed: %w", err)
}
return nil
}