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,参看我上一篇文章:

相关推荐
Omigeq13 小时前
1.2.2 - 采样搜索算法(以RRT和RRT*为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·机器人
m0_5312371713 小时前
C语言-操作符进阶
c语言·开发语言
q12345678909814 小时前
FNN sin predict
开发语言·python
沐知全栈开发14 小时前
C++ 多态
开发语言
zihan032114 小时前
若依(RuoYi)框架核心升级:全面适配 SpringData JPA,替换 MyBatis 持久层方案
java·开发语言·前端框架·mybatis·若依升级springboot
先做个垃圾出来………14 小时前
Python字节串“b“前缀
开发语言·python
无限进步_14 小时前
21. 合并两个有序链表 - 题解与详细分析
c语言·开发语言·数据结构·git·链表·github·visual studio
神奇大叔14 小时前
Java 配置文件记录
java·开发语言
三水彡彡彡彡15 小时前
C++拷贝函数:const与引用的高效实践
开发语言·c++
悠闲蜗牛�15 小时前
深入浅出Spring Boot 3.x:新特性全解析与实战指南
开发语言·python