标准库与实战
约 60 分钟B1: io/net/http 与 JSON
掌握 Go 的 I/O 操作、HTTP 客户端/服务端、JSON 编解码
学习目标
- 1.理解 io.Reader/Writer 接口的设计哲学
- 2.实现基础 HTTP 服务和客户端调用
- 3.掌握 encoding/json 的使用技巧
课程内容
本课时将帮助你快速掌握相关知识。以下是示例代码:
main.go
1package main2 3import "fmt"4 5func main() {6 fmt.Println("Hello, Go!")7 8 // Go 的变量声明9 var name string = "TypeScript Developer"10 age := 25 // 短变量声明11 12 fmt.Printf("Name: %s, Age: %d\n", name, age)13}上面的代码演示了 Go 的基本语法,包括包声明、导入和变量声明。 注意第 8 行的短变量声明语法 :=,这是 Go 的特色。
与 TypeScript 对比
example.ts
// TypeScript 版本const name: string = "TypeScript Developer";const age = 25; // 类型推断 console.log(`Name: ${name}, Age: ${age}`);实战练习
实现简单的 REST API
进阶
创建一个返回 JSON 数据的 HTTP 端点
初始代码
Go
1package main2 3import (4 "encoding/json"5 "net/http"6)7 8type User struct {9 ID int `json:"id"`10 Name string `json:"name"`11}12 13func userHandler(w http.ResponseWriter, r *http.Request) {14 // 请补全:返回一个 User 的 JSON 响应15}16 17func main() {18 http.HandleFunc("/user", userHandler)19 http.ListenAndServe(":8080", nil)20}查看参考答案
Go
1package main2 3import (4 "encoding/json"5 "net/http"6)7 8type User struct {9 ID int `json:"id"`10 Name string `json:"name"`11}12 13func userHandler(w http.ResponseWriter, r *http.Request) {14 user := User{ID: 1, Name: "Alice"}15 w.Header().Set("Content-Type", "application/json")16 json.NewEncoder(w).Encode(user)17}18 19func main() {20 http.HandleFunc("/user", userHandler)21 http.ListenAndServe(":8080", nil)22}