当前位置: 首页 > article >正文

go-zero学习笔记

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

文章目录

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

1、go-zero核心库

1.1 路由与处理器

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 日志中间件

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 请求上下文

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(远程过程调用)、服务治理、持久化层(数据层)、配置与日志、定时任务、监控与报警、微服务架构支持


http://www.kler.cn/a/597894.html

相关文章:

  • 河南大学数据库实验6
  • 为WordPress自定义一个留言板
  • Nginx请求头Hos头攻击
  • 解决Centos使用yum命令报错“Cannot find a valid baseurl for repo: base/7/x86_64”问题
  • 服务器负载均衡
  • 计算机视觉yolov8模型应用-学习笔记
  • mujoco传感器数据读取的正确姿势
  • 基于深度学习的图片识别系统(上)
  • DFS深搜
  • AI开源项目
  • 优选算法的睿智之林:前缀和专题(一)
  • 2.2.盈亏平衡分析
  • MySQL 索引下推
  • React 18 如何定义变量,及赋值 与渲染
  • Linux常用的命令
  • [AI速读]混合验证方案:如何高效解决RISC-V向量扩展的验证难题
  • Nginx如何处理请求
  • Modbus协议编程读写流程图大全
  • DeepSeek对KVM环境下创建共享iSCSI存储的指导
  • 使用单调栈在O(n)时间复杂度内计算直方图中的最大矩形面积