蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

综合实测 Go 并发通道、语法概览、httptest JSON 接口、Worker 池与常见陷阱

GO本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。explore_intro.go
explore_intro.go433 行
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"math"
	"net/http"
	"net/http/httptest"
	"os"
	"reflect"
	"runtime"
	"sort"
	"strings"
	"sync"
)

type CaseResult struct {
	Name     string `json:"name"`
	Summary  string `json:"summary"`
	Expected any    `json:"expected"`
	Actual   any    `json:"actual"`
	Passed   bool   `json:"passed"`
}

type LabOutput struct {
	Version string       `json:"version"`
	Cases   []CaseResult `json:"cases"`
}

func makeCase(name, summary string, expected, actual any) CaseResult {
	return CaseResult{
		Name:     name,
		Summary:  summary,
		Expected: expected,
		Actual:   actual,
		Passed:   reflect.DeepEqual(expected, actual),
	}
}

func add(a, b int) int {
	return a + b
}

func divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, errors.New("除数不能为零")
	}
	return a / b, nil
}

func swapStrings(x, y string) (string, string) {
	return y, x
}

type User struct {
	Name  string
	Email string
	age   int
}

func (u User) Greet() string {
	return fmt.Sprintf("你好,我是 %s,邮箱是 %s", u.Name, u.Email)
}

func (u *User) Birthday() {
	u.age++
}

type Shape interface {
	Area() float64
	Perimeter() float64
}

type Circle struct {
	Radius float64
}

func (c Circle) Area() float64      { return math.Pi * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius }

type Rectangle struct {
	Width, Height float64
}

func (r Rectangle) Area() float64      { return r.Width * r.Height }
func (r Rectangle) Perimeter() float64 { return 2 * (r.Width + r.Height) }

type APIResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "仅支持 GET 请求", http.StatusMethodNotAllowed)
		return
	}
	name := r.URL.Query().Get("name")
	if name == "" {
		name = "Gopher"
	}
	resp := APIResponse{
		Code:    200,
		Message: fmt.Sprintf("你好,%s!欢迎访问 Go HTTP 服务", name),
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	_ = json.NewEncoder(w).Encode(resp)
}

type customErr struct {
	msg string
}

func (e *customErr) Error() string {
	return e.msg
}

func main() {
	var cases []CaseResult

	// 1. goroutine_channel_workers
	const numJobs = 5
	jobs := make(chan int, numJobs)
	results := make(chan int, numJobs)
	var wg sync.WaitGroup
	for w := 1; w <= 3; w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := range jobs {
				results <- j * 2
			}
		}()
	}
	for j := 1; j <= numJobs; j++ {
		jobs <- j
	}
	close(jobs)
	wg.Wait()
	close(results)
	var got []int
	for r := range results {
		got = append(got, r)
	}
	sort.Ints(got)
	cases = append(cases, makeCase(
		"goroutine_channel_workers",
		"启动 3 个工作协程消费带缓冲 jobs 通道并汇总双倍结果",
		[]int{2, 4, 6, 8, 10},
		got,
	))

	// 2. static_types_and_inference
	var name string = "gopher"
	var version = 1.24
	count := 100
	message := "Hello Go"
	x, y := 10, 20
	cases = append(cases, makeCase(
		"static_types_and_inference",
		"验证显式声明、类型推断、短变量声明及多变量声明的静态类型",
		map[string]any{
			"name_type":    "string",
			"version_type": "float64",
			"count_type":   "int",
			"message_type": "string",
			"summary":      "gopher 1.24 100 Hello Go 10 20",
		},
		map[string]any{
			"name_type":    reflect.TypeOf(name).String(),
			"version_type": reflect.TypeOf(version).String(),
			"count_type":   reflect.TypeOf(count).String(),
			"message_type": reflect.TypeOf(message).String(),
			"summary":      fmt.Sprintf("%s %.2f %d %s %d %d", name, version, count, message, x, y),
		},
	))

	// 3. hello_world_and_modules
	helloLines := []string{"Hello, Gopher!", "欢迎来到 Go 语言的世界"}
	goModSample := "module example.com/my-go-project\n\ngo 1.22\n"
	cases = append(cases, makeCase(
		"hello_world_and_modules",
		"验证入口程序输出格式与 go.mod 模块路径声明格式",
		map[string]any{
			"lines":       []string{"Hello, Gopher!", "欢迎来到 Go 语言的世界"},
			"has_module":  true,
			"has_version": true,
		},
		map[string]any{
			"lines":       helloLines,
			"has_module":  strings.Contains(goModSample, "module example.com/my-go-project"),
			"has_version": strings.Contains(goModSample, "go 1.22"),
		},
	))

	// 4. variables_and_constants
	var age int = 25
	var score float64
	score = 98.5
	devName := "gopher"
	vx, vy := 10, 20
	const Pi = 3.14159
	const AppName = "BlueSkyGo"
	cases = append(cases, makeCase(
		"variables_and_constants",
		"验证四种变量声明形式与常量定义值",
		"gopher 25 98.5 10 20 3.14159 BlueSkyGo",
		fmt.Sprintf("%s %d %.1f %d %d %.5f %s", devName, age, score, vx, vy, Pi, AppName),
	))

	// 5. control_flow_if_for_switch
	gradeScore := 85
	var grade string
	if gradeScore >= 90 {
		grade = "A"
	} else if gradeScore >= 60 {
		grade = "B"
	} else {
		grade = "C"
	}
	var seq []int
	for i := 0; i < 5; i++ {
		seq = append(seq, i)
	}
	sum10, n := 0, 1
	for n <= 10 {
		sum10 += n
		n++
	}
	fruits := []string{"apple", "banana", "cherry"}
	var indexed []string
	for idx, fruit := range fruits {
		indexed = append(indexed, fmt.Sprintf("%d:%s", idx, fruit))
	}
	day := "周一"
	var dayNote string
	switch day {
	case "周一":
		dayNote = "新的一周开始了"
	case "周五":
		dayNote = "周末快到了"
	default:
		dayNote = "普通的一天"
	}
	cases = append(cases, makeCase(
		"control_flow_if_for_switch",
		"验证 if/else if/else、三种 for 循环形式与自动 break 的 switch 分支",
		map[string]any{
			"grade":    "B",
			"seq":      []int{0, 1, 2, 3, 4},
			"sum10":    55,
			"indexed":  []string{"0:apple", "1:banana", "2:cherry"},
			"day_note": "新的一周开始了",
		},
		map[string]any{
			"grade":    grade,
			"seq":      seq,
			"sum10":    sum10,
			"indexed":  indexed,
			"day_note": dayNote,
		},
	))

	// 6. functions_and_error_handling
	q, err1 := divide(10, 2)
	_, err2 := divide(10, 0)
	s1, s2 := swapStrings("Go", "Hello")
	cases = append(cases, makeCase(
		"functions_and_error_handling",
		"验证多返回值函数、(result, error) 显式错误处理与空白标识符忽略返回值",
		map[string]any{
			"add":      30,
			"div_ok":   5.0,
			"div_nil":  true,
			"div_zero": "除数不能为零",
			"swapped":  "Hello Go",
		},
		map[string]any{
			"add":      add(10, 20),
			"div_ok":   q,
			"div_nil":  err1 == nil,
			"div_zero": err2.Error(),
			"swapped":  s1 + " " + s2,
		},
	))

	// 7. struct_methods_receivers
	u := User{Name: "Alice", Email: "alice@example.com", age: 25}
	beforeAge := u.age
	greeting := u.Greet()
	u.Birthday()
	afterAge := u.age
	cases = append(cases, makeCase(
		"struct_methods_receivers",
		"验证结构体值接收者方法与指针接收者修改原始字段行为",
		map[string]any{
			"greeting":   "你好,我是 Alice,邮箱是 alice@example.com",
			"before_age": 25,
			"after_age":  26,
		},
		map[string]any{
			"greeting":   greeting,
			"before_age": beforeAge,
			"after_age":  afterAge,
		},
	))

	// 8. implicit_interface_polymorphism
	var shapes []Shape = []Shape{Circle{Radius: 5}, Rectangle{Width: 4, Height: 6}}
	var metrics []string
	for _, s := range shapes {
		metrics = append(metrics, fmt.Sprintf("%.2f/%.2f", s.Area(), s.Perimeter()))
	}
	cases = append(cases, makeCase(
		"implicit_interface_polymorphism",
		"验证 Circle 与 Rectangle 隐式实现 Shape 接口的多态调用",
		[]string{"78.54/31.42", "24.00/20.00"},
		metrics,
	))

	// 9. http_json_handler_and_worker_pool
	req1 := httptest.NewRequest(http.MethodGet, "/hello?name=Go%E5%BC%80%E5%8F%91%E8%80%85", nil)
	rec1 := httptest.NewRecorder()
	helloHandler(rec1, req1)
	var resp1 APIResponse
	if err := json.Unmarshal(rec1.Body.Bytes(), &resp1); err != nil {
		panic(err)
	}

	req2 := httptest.NewRequest(http.MethodGet, "/hello", nil)
	rec2 := httptest.NewRecorder()
	helloHandler(rec2, req2)
	var resp2 APIResponse
	if err := json.Unmarshal(rec2.Body.Bytes(), &resp2); err != nil {
		panic(err)
	}

	req3 := httptest.NewRequest(http.MethodPost, "/hello", nil)
	rec3 := httptest.NewRecorder()
	helloHandler(rec3, req3)

	const poolJobs = 10
	pJobs := make(chan int, poolJobs)
	pRes := make(chan int, poolJobs)
	var pwg sync.WaitGroup
	for w := 1; w <= 3; w++ {
		pwg.Add(1)
		go func() {
			defer pwg.Done()
			for j := range pJobs {
				pRes <- j * j
			}
		}()
	}
	for j := 1; j <= poolJobs; j++ {
		pJobs <- j
	}
	close(pJobs)
	go func() {
		pwg.Wait()
		close(pRes)
	}()
	var squares []int
	for r := range pRes {
		squares = append(squares, r)
	}
	sort.Ints(squares)

	cases = append(cases, makeCase(
		"http_json_handler_and_worker_pool",
		"使用 httptest 验证 net/http JSON 路由处理与 3 协程 Worker 池平方计算",
		map[string]any{
			"get_named_code":   200,
			"get_named_msg":    "你好,Go开发者!欢迎访问 Go HTTP 服务",
			"get_default_msg":  "你好,Gopher!欢迎访问 Go HTTP 服务",
			"post_status_code": 405,
			"squares":          []int{1, 4, 9, 16, 25, 36, 49, 64, 81, 100},
		},
		map[string]any{
			"get_named_code":   resp1.Code,
			"get_named_msg":    resp1.Message,
			"get_default_msg":  resp2.Message,
			"post_status_code": rec3.Code,
			"squares":          squares,
		},
	))

	// 10. common_pitfalls_verification
	_, readErr := os.ReadFile("/nonexistent-config-file-for-lab.txt")
	baseSlice := []int{1, 2, 3, 4}
	shared := baseSlice[:2]
	copied := make([]int, 2)
	copy(copied, baseSlice[:2])
	shared[0] = 99
	copied[1] = 88

	var typedNilPtr *customErr = nil
	var ifaceHoldingNil error = typedNilPtr
	var pureNilIface error = nil

	cases = append(cases, makeCase(
		"common_pitfalls_verification",
		"实测显式文件错误检测、切片共享底层数组与 copy 隔离、nil 指针装入接口后非 nil 陷阱",
		map[string]any{
			"read_not_exist":           true,
			"base_affected_by_shared":  99,
			"base_unaffected_by_copy":  2,
			"typed_nil_iface_not_nil":  true,
			"pure_nil_iface_is_nil":    true,
		},
		map[string]any{
			"read_not_exist":           errors.Is(readErr, os.ErrNotExist),
			"base_affected_by_shared":  baseSlice[0],
			"base_unaffected_by_copy":  baseSlice[1],
			"typed_nil_iface_not_nil":  ifaceHoldingNil != nil,
			"pure_nil_iface_is_nil":    pureNilIface == nil,
		},
	))

	out := LabOutput{
		Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
		Cases:   cases,
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetEscapeHTML(false)
	enc.SetIndent("", "  ")
	if err := enc.Encode(out); err != nil {
		panic(err)
	}
}
本例需在 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。

入口文件:projects/go-intro-lab/explore_intro.go

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore_intro.go,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Go

课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip

下载课程关联工程包:Go

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1173.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习