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

相关推荐
Kila_17 分钟前
【iOS(swift)笔记-13】App版本不升级时本地数据库sqlite更新逻辑一
数据库·笔记
Kila_19 分钟前
【iOS(swift)笔记-14】App版本不升级时本地数据库sqlite更新逻辑二
数据库·笔记
Cxzzzzzzzzzz35 分钟前
go语言的GMP(基础)
开发语言·性能优化·golang
Lester_110137 分钟前
嵌入式学习笔记 - FreeRTOS关于vApplicationGetIdleTaskMemory
笔记·stm32·学习·freertos
大写-凌祁1 小时前
GLIDE论文阅读笔记与DDPM(Diffusion model)的原理推导
论文阅读·人工智能·笔记·python·深度学习·机器学习·计算机视觉
小葡萄20252 小时前
黑马程序员C++核心编程笔记--4 类和对象--多态
java·c++·笔记
胡萝卜3.03 小时前
c语言内存函数
c语言·开发语言·笔记·学习方法
职业考试资料墙3 小时前
登高架设作业实操考试需要注意哪些安全细节?
学习·考试·题库·考证
Moonnnn.3 小时前
【PCB设计】STM32开发板——原理图设计(电源部分)
笔记·stm32·单片机·嵌入式硬件·学习
Rousson3 小时前
硬件学习笔记--62 MCU的ECC功能简介
笔记·单片机·学习