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

相关推荐
海尔辛2 小时前
学习黑客Bash 脚本
开发语言·学习·bash
夏季疯2 小时前
学习笔记:黑马程序员JavaWeb开发教程(2025.3.30)
java·笔记·学习
乘风破浪的咸鱼君3 小时前
RabbitMq学习(第一天)
学习·rabbitmq
Lucky高3 小时前
学习Python的第一天之网络爬虫
爬虫·python·学习
unique_pursuit4 小时前
《Overlapping Experiment Infrastructure: More, Better, Faster》论文阅读笔记
论文阅读·笔记
赶飞机偏偏下雨4 小时前
【前端笔记】CSS 选择器的常见用法
前端·css·笔记
Echo``4 小时前
2:点云处理—3D相机开发
人工智能·笔记·数码相机·算法·计算机视觉·3d·视觉检测
triticale4 小时前
【Spring】Spring MVC笔记
笔记·spring·mvc
chushiyunen4 小时前
draw.io流程图使用笔记
笔记·流程图·draw.io
LVerrrr5 小时前
Missashe考研日记-day34
学习·考研