go-zero学习笔记

内容不多,只有部分笔记,剩下的没有继续学下去,包括路由与处理器、日志中间件、请求上下文

文章目录

  • 1、go-zero核心库
    • [1.1 路由与处理器](#1.1 路由与处理器)
    • [1.2 日志中间件](#1.2 日志中间件)
    • [1.3 请求上下文](#1.3 请求上下文)

1、go-zero核心库

1.1 路由与处理器

go 复制代码
package main

import (
	"github.com/zeromicro/go-zero/rest"
	"net/http"
)

func main() {
	r := rest.MustNewServer(rest.RestConf{
		Port: 8080, // 设置监听端口
	})
	defer r.Stop()

	// 定义一个处理器
	r.AddRoute(rest.Route{
		Method:  http.MethodGet,
		Path:    "/hello",
		Handler: helloHandler,
	})

	r.Start()
}

// helloHandler 是处理 GET 请求的函数
func helloHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello, Go-zero!"))
}

1.2 日志中间件

go 复制代码
package main

import (
	"fmt"
	"github.com/zeromicro/go-zero/rest"
	"net/http"
)

func main() {
	fmt.Println("http://127.0.0.1:8081/hello")
	r := rest.MustNewServer(rest.RestConf{
		Port: 8081,
	})
	defer r.Stop()

	// 使用中间件来记录请求日志
	r.Use(logMiddleware)

	r.AddRoute(rest.Route{
		Method:  http.MethodGet,
		Path:    "/hello",
		Handler: helloHandler,
	})

	r.Start()
}

func logMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Printf("Received request: %s %s\n", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}



// helloHandler 处理 GET 请求
func helloHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello, Go-zero!"))
}

1.3 请求上下文

go 复制代码
package main

import (
	"fmt"
	"github.com/zeromicro/go-zero/rest"
	"net/http"
)

func main() {
	r := rest.MustNewServer(rest.RestConf{
		Port: 8080,
	})
	defer r.Stop()
	r.AddRoute(rest.Route{
		Method:  http.MethodGet,
		Path:    "/hello",
		Handler: helloHandler,
	})
	r.Start()
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	user := r.Context().Value("user")
	if user != nil {
		fmt.Fprintf(w, "Hello, %s!", user)
	} else {
		fmt.Fprintf(w, "Hello, %s!", r.FormValue("name"))
	}

}

API模式生成器、RPC(远程过程调用)、服务治理、持久化层(数据层)、配置与日志、定时任务、监控与报警、微服务架构支持

相关推荐
Mr Sorry2 小时前
Non-stationary Diffusion For Probabilistic Time Series Forecasting论文阅读笔记
论文阅读·笔记
南猿北者3 小时前
Cmake学习笔记
笔记·学习·策略模式
码小文4 小时前
Altium Designer 22使用笔记(8)---PCB电气约束设置
笔记·嵌入式硬件·硬件工程·ad22
diablobaal4 小时前
云计算学习100天-第26天
学习·云计算
测试老哥5 小时前
pytest+requests+allure自动化测试接入Jenkins学习
自动化测试·软件测试·学习·测试工具·职场和发展·jenkins·pytest
UserNamezhangxi6 小时前
kotlin 协程笔记
java·笔记·kotlin·协程
diablobaal8 小时前
云计算学习100天-第21天
学习
bianshaopeng9 小时前
ubuntu go 环境变量配置
开发语言·ubuntu·golang
元清加油9 小时前
【Goland】:协程和通道
服务器·开发语言·后端·网络协议·golang
lpfasd1239 小时前
01_Go语言基础与环境搭建
开发语言·后端·golang