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

相关推荐
知识分享小能手7 分钟前
CSS3学习教程,从入门到精通,CSS3 定位布局页面知识点及案例代码(18)
前端·javascript·css·学习·html·css3·html5
云半S一20 分钟前
性能测试笔记
经验分享·笔记·压力测试
demonlg011220 分钟前
Go 语言 fmt 模块的完整方法详解及示例
开发语言·后端·golang
云上艺旅26 分钟前
K8S学习之基础四十三:k8s中部署elasticsearch
学习·elasticsearch·云原生·kubernetes
齐尹秦40 分钟前
HTML5 拖放(Drag and Drop)学习笔记
笔记·学习·html5
sakabu1 小时前
Linux安装MySQL数据库并使用C语言进行数据库开发
linux·c语言·数据库·笔记·mysql·数据库开发
东方韡璟2 小时前
Objective-C语言的数据可视化
开发语言·后端·golang
Amor风信子2 小时前
【简单学习】Prompt Engineering 提示词工程
学习·chatgpt·prompt
chxii2 小时前
6.go语言函数
开发语言·后端·golang