golang构建Web应用的实战指南插件库Web Application with Go the Anti-Textbook的使用

Golang构建Web应用的实战指南插件库Web Application with Go the Anti-Textbook的使用

关于本书

这是一个易于理解的基于示例的教程,面向那些了解一些Go语言但对Web开发一无所知,并想学习如何用Go编写Web服务器的读者。随着章节的推进,你将创建一个待办事项列表应用程序。

如何使用

请使用code文件夹中的front end文件夹获取Tasks项目的index.html文件,并在阅读本教程时使用它。

示例代码

以下是一个简单的Go Web应用程序示例,展示了如何使用net/http包创建一个基本的Web服务器:

package main

import (
    "fmt"
    "net/http"
)

// 处理根路径请求
func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "欢迎使用Go Web应用!")
}

func main() {
    // 注册路由处理函数
    http.HandleFunc("/", handler)
    
    // 启动服务器并监听8080端口
    fmt.Println("服务器正在运行,访问 http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

配套资源

我们有一个YouTube系列和一个完整功能的Web应用程序作为配套文档。Tasks是你阅读本书时将创建的应用程序。

如果你更喜欢通过观看学习,可以查看YouTube系列。该系列对应的代码已发布为分支,每个视频都有特定的分支。

贡献

我们欢迎所有Pull Requests,请在开始工作前先提出一个issue!

哲学

  • 通过本书我们想教授如何使用Go开发Web应用程序。我们期望读者了解Go的基础知识,但我们假设读者对如何编写Web应用程序一无所知。
  • 本书由章节组成,如果主题过大无法放入一章,则尽可能分成多章。
  • 每个章节应分成带有有意义标题的逻辑部分或节,这些部分将教授读者一些东西。
  • 每个概念都应伴随着Go代码(如果有的话),对于"预览"类型的节,编写Go伪代码,只编写必要的代码部分并保持其他所有内容。
  • 代码宽度不应超过80个字符,因为在书的PDF版本中代码会不可见。
  • “简洁是智慧的灵魂”,请保持描述尽可能简短。这并不意味着我们跳过它,而是尝试用尽可能简单的词语解释它。在这种情况下,请解释概念。
  • 在我们创建的待办事项列表管理器中,我们将努力实现尽可能多的功能,以给读者提供实际的Go编程体验。在我们重新实现标准库内容的情况下,我们应该清楚地提到它。

许可证

本书许可证:CC BY-SA 3.0许可证

注意事项

  1. Go编程基础部分改编自astaxie的build-web-application-with-golang
  2. 封面上的gopher图片取自golang.org/doc/gopher/appenginegophercolor.jpg,未作修改
  3. 数据库章节改编自VividCortex的go-database-sql-tutorial,并进行了修改

更多关于golang构建Web应用的实战指南插件库Web Application with Go the Anti-Textbook的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang构建Web应用的实战指南插件库Web Application with Go the Anti-Textbook的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用《Web Application with Go the Anti-Textbook》构建Go Web应用实战指南

《Web Application with Go the Anti-Textbook》是一本专注于用Go语言构建Web应用的实用指南,它采用"反教科书"的方式,强调实践而非理论。下面我将介绍如何使用这本书中的方法和一些关键插件库来构建Go Web应用。

核心概念

这本书的核心思想是:

  • 从实际需求出发而非从理论概念开始
  • 强调代码组织和项目结构
  • 关注安全性和性能
  • 使用标准库为主,适度引入第三方库

常用插件库推荐

虽然书中提倡尽量使用标准库,但也推荐了一些实用的第三方库:

1. 路由库

// 使用标准库的http.ServeMux
mux := http.NewServeMux()
mux.HandleFunc("/", homeHandler)
mux.HandleFunc("/about", aboutHandler)

// 或者使用轻量级第三方路由chi
import "github.com/go-chi/chi/v5"

r := chi.NewRouter()
r.Get("/", homeHandler)
r.Get("/about", aboutHandler)

2. 数据库访问

// 使用database/sql标准接口+驱动
import (
    "database/sql"
    _ "github.com/lib/pq" // PostgreSQL驱动
)

db, err := sql.Open("postgres", "user=postgres dbname=mydb sslmode=disable")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

3. 模板处理

// 使用标准库html/template
import "html/template"

tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/home.html"))
err := tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
}

4. 中间件处理

// 自定义中间件示例
func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("Received request: %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

// 使用
mux := http.NewServeMux()
// ...路由设置
wrappedMux := loggingMiddleware(mux)

项目结构建议

书中推荐的典型项目结构:

/myapp
  /cmd
    /web
      main.go      # 应用入口
  /internal
    /handlers     # HTTP处理器
    /models       # 数据模型
    /middleware   # 中间件
  /pkg
    /database     # 数据库相关
    /config       # 配置处理
  /ui
    /static       # 静态文件
    /templates    # HTML模板
  go.mod
  go.sum

安全实践

书中强调的安全要点代码示例:

// 1. CSRF防护
import "github.com/gorilla/csrf"

csrfMiddleware := csrf.Protect(
    []byte("32-byte-long-auth-key"),
    csrf.Secure(false), // 仅开发环境设为false
)

// 2. 安全头部
func secureHeaders(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("X-XSS-Protection", "1; mode=block")
        w.Header().Set("X-Frame-Options", "deny")
        w.Header().Set("X-Content-Type-Options", "nosniff")
        next.ServeHTTP(w, r)
    })
}

// 3. SQL注入防护 - 使用参数化查询
stmt, err := db.Prepare("SELECT * FROM users WHERE email = $1")
if err != nil {
    log.Fatal(err)
}
rows, err := stmt.Query(email)

实战示例:简单的博客系统

// main.go
package main

import (
    "database/sql"
    "log"
    "net/http"
    
    _ "github.com/lib/pq"
    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
)

func main() {
    // 初始化数据库
    db, err := sql.Open("postgres", "user=postgres dbname=blog sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
    
    // 创建路由
    r := chi.NewRouter()
    
    // 中间件
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)
    
    // 路由
    r.Get("/", homeHandler(db))
    r.Get("/articles/{id}", articleHandler(db))
    
    // 静态文件
    r.Handle("/static/*", http.StripPrefix("/static/", 
        http.FileServer(http.Dir("ui/static"))))
    
    log.Println("Starting server on :4000")
    http.ListenAndServe(":4000", r)
}

func homeHandler(db *sql.DB) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // 查询文章列表
        rows, err := db.Query("SELECT id, title FROM articles ORDER BY created_at DESC LIMIT 10")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer rows.Close()
        
        // 处理结果并渲染模板
        // ...
    }
}

总结

《Web Application with Go the Anti-Textbook》提倡的Go Web开发哲学是:

  1. 优先使用标准库
  2. 保持简单和明确
  3. 重视代码组织和可维护性
  4. 安全性不是可选项而是必须项
  5. 性能考虑从设计开始

通过这本书的方法,你可以构建出高效、安全且易于维护的Go Web应用,而不会被过度设计的框架所束缚。

回到顶部