go语言实现gateway简单样例

目录

1、代码实现样例:

2、postman调用


1、代码实现样例:

gateway转发的url根据实际去调整,转发访问的url是否存在token,也根据实际情况去调整:

复制代码
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/afex/hystrix-go/hystrix"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	// 设置路由
	r.GET("/service/:service", handleRequest)

	// 启动服务
	if err := r.Run(":8081"); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

func handleRequest(c *gin.Context) {
	service := c.Param("service")
	commandName := "service_" + service

	// 使用 Hystrix 实现服务熔断
	hystrix.ConfigureCommand(commandName, hystrix.CommandConfig{
		Timeout:               1000, // 超时时间(毫秒)
		MaxConcurrentRequests: 100,  // 最大并发请求数
		ErrorPercentThreshold: 25,   // 错误百分比阈值
	})

	hystrix.Do(commandName, func() error {
		// 获取客户端传入的 token
		token := c.GetHeader("Authorization")

		fmt.Println("token", token)

		// 创建请求
		req, err := http.NewRequest("GET", "http://localhost:8080/"+service, nil)
		if err != nil {
			return err
		}

		// 添加认证 token
		req.Header.Set("Authorization", token)

		// 发送请求
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			return err
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		// 将目标服务的响应返回给客户端
		c.Status(resp.StatusCode)
		fmt.Println("status:", string(body))
		_, err = c.Writer.Write(body)
		return err
	}, func(err error) error {
		// 处理熔断
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Service unavailable"})
		return nil
	})
}

2、postman调用

使用先前生成的token,服务转发的之前服务的url,参看我上一篇文章:

相关推荐
两点王爷9 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
微笑星河q10 小时前
C++高阶之【多态】
开发语言·c++
ClkLog-开源埋点用户分析13 小时前
【产品说明】【埋点分析】ClkLog 商业版 Java 运行环境安全更新说明
java·开发语言
yuzhiboyouye14 小时前
《阿里巴巴 Java 开发手册》的 MySQL 核心规范
java·开发语言·mysql
郝学胜-神的一滴15 小时前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
geovindu15 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
时间的情敌17 小时前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
Amumu1213817 小时前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript
敲上瘾18 小时前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3