Go Web 编程实战Go Web 编程实战
首页
课程导读
首页
课程导读
  • 课程导读
  • 课程目录

    • Go基础语法精要
    • Web基础与HTTP处理
    • Gin框架入门
    • 路由与中间件
    • 数据库操作
    • 模板渲染
    • 错误处理与日志
    • 测试与部署
    • 高级中间件模式
    • 微服务架构
    • 性能优化
    • 安全最佳实践
    • 项目结构与代码组织

Web基础与HTTP处理

1. HTTP基础

HTTP协议是Web开发的基础,Go的标准库net/http提供了完整的HTTP服务器和客户端实现。

2. 创建简单HTTP服务器

package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", helloHandler)
    fmt.Println("Server starting on :8080...")
    http.ListenAndServe(":8080", nil)
}

3. 处理HTTP请求

func requestInfo(w http.ResponseWriter, r *http.Request) {
    // 获取请求方法
    method := r.Method
    
    // 获取请求路径
    path := r.URL.Path
    
    // 获取查询参数
    name := r.URL.Query().Get("name")
    
    // 获取请求头
    userAgent := r.Header.Get("User-Agent")
    
    fmt.Fprintf(w, "Method: %s\nPath: %s\nName: %s\nUserAgent: %s", 
        method, path, name, userAgent)
}

4. 返回不同响应

func jsonResponse(w http.ResponseWriter, r *http.Request) {
    // 设置Content-Type
    w.Header().Set("Content-Type", "application/json")
    
    // 返回JSON数据
    data := map[string]interface{}{
        "status":  "success",
        "message": "Hello, JSON!",
    }
    json.NewEncoder(w).Encode(data)
}

func errorResponse(w http.ResponseWriter, r *http.Request) {
    // 返回错误状态码
    w.WriteHeader(http.StatusNotFound)
    fmt.Fprint(w, "404 Not Found")
}

5. 静态文件服务

func main() {
    // 提供静态文件服务
    fs := http.FileServer(http.Dir("static"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))
    
    http.ListenAndServe(":8080", nil)
}

提示:这些是Go标准库提供的Web基础功能,实际开发中我们通常会使用框架(如Gin)来简化开发,但理解这些底层原理非常重要。

Prev
Go基础语法精要
Next
Gin框架入门