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

相关推荐
进击的程序猿~3 小时前
Go Zero源码阅读1
后端·golang
星幻元宇VR9 小时前
公共安全实训展厅设备【人防知识学习系统】
科技·学习·安全
李燚10 小时前
Go 项目怎么组织:DDD 4 层 vs MVC vs 脚本式
开发语言·golang·mvc·ddd·agent框架·eino
心中有国也有家12 小时前
AtomGit Flutter 鸿蒙客户端:情绪日记的时间线实现
学习·flutter·华为·harmonyos
百里香酚兰13 小时前
【python学习笔记】pyttsx3库疑似只播报一次语音
笔记·python·学习
恣逍信点13 小时前
《凌微经》助读:本体论根基——“无之自悖”与“形性一体”
人工智能·科技·学习·程序人生·生活·交友·哲学
Generalzy13 小时前
从 Web 页面到桌面应用:用 Go + WebView 构建一个轻量级桌面框架
开发语言·前端·golang
chh56315 小时前
C++--string
java·开发语言·网络·c++·学习
chnyi6_ya15 小时前
论文阅读笔记:VideoWeaver — 面向智能体长视频生成的技能评估与进化
论文阅读·笔记·音视频
J_yyy15 小时前
基于Reactor的文件管理服务开发笔记
c++·笔记·reactor·多线程编程·muduo