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

相关推荐
Overboom3 小时前
[C++] --- 常用设计模式
开发语言·c++·设计模式
Univin3 小时前
C++(10.4)
开发语言·数据结构·c++
KyollBM3 小时前
每日羊题 (质数筛 + 数学 | 构造 + 位运算)
开发语言·c++·算法
Paul_09205 小时前
golang面经——map模块和sync.Map模块
开发语言
Univin5 小时前
C++(10.5)
开发语言·c++·算法
haogexiaole5 小时前
Java高并发常见架构、处理方式、api调优
java·开发语言·架构
张人玉6 小时前
C# 通讯关键类的API
开发语言·c#
froginwe116 小时前
R 数组:深入解析与高效使用
开发语言
tao3556676 小时前
【Python刷力扣hot100】283. Move Zeroes
开发语言·python·leetcode