真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

Golang如何實現(xiàn)簡單的API網(wǎng)關(guān)

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供玉泉網(wǎng)站建設、玉泉做網(wǎng)站、玉泉網(wǎng)站設計、玉泉網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、玉泉企業(yè)網(wǎng)站模板建站服務,十年玉泉做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡服務。

下面由Golang教程欄目給大家介紹Golang實現(xiàn)簡單的API網(wǎng)關(guān)的方法 ,希望對需要的朋友有所幫助!

在最近的一個項目中,采用了微服務架構(gòu)-go-kit進行后端的開發(fā)。在微服務架構(gòu)風格中,一個大應用被拆分成為了多個小的服務系統(tǒng)提供出來,這些小的系統(tǒng)他們可以自成體系,也就是說這些小系統(tǒng)可以擁有自己的數(shù)據(jù)庫,框架甚至語言等,因此我們需要設計一個API 網(wǎng)關(guān)(API Gataway),其實網(wǎng)上已經(jīng)有較多現(xiàn)成的實現(xiàn)框架,但是本項目的需求是比較簡單的,因此將使用Golang自行實現(xiàn)。

實現(xiàn)

API網(wǎng)關(guān)是一個服務器,是系統(tǒng)的唯一入口。從面向?qū)ο笤O計的角度看,它與外觀模式類似。API網(wǎng)關(guān)封裝了系統(tǒng)內(nèi)部架構(gòu),為每個客戶端提供一個定制的API。它可能還具有其它職責,如身份驗證、監(jiān)控、負載均衡、緩存、請求分片與管理、靜態(tài)響應處理。

用于實現(xiàn)API網(wǎng)關(guān)的技術(shù)有很多,大致分為這么幾類:

通用反向代理:NginxHaproxy、……網(wǎng)絡編程框架:Netty、Servlet、……API網(wǎng)關(guān)框架:Spring Cloud Gateway、Zuul、Zuul2、……

API網(wǎng)關(guān)最基本的功能就是反向代理。其實現(xiàn)方式有很多,本文將基于標準庫net/http/httputil包中的ReverseProxy類型來實現(xiàn)實現(xiàn)一個簡單的反向代理。反向代理的實現(xiàn)主要涉及到func NewSingleHostReverseProxy(target *url.URL) *ReverseProxytype ReverseProxy。

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy
// NewSingleHostReverseProxy returns a new ReverseProxy that routes// URLs to the scheme, host, and base path provided in target. If the// target's path is "/base" and the incoming request was for "/dir",// the target request will be for /base/dir.// NewSingleHostReverseProxy does not rewrite the Host header.// To rewrite Host headers, use ReverseProxy directly with a custom// Director policy.func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
	targetQuery := target.RawQuery
	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
		if targetQuery == "" || req.URL.RawQuery == "" {
			req.URL.RawQuery = targetQuery + req.URL.RawQuery		} else {
			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery		}
		if _, ok := req.Header["User-Agent"]; !ok {
			// explicitly disable User-Agent so it's not set to default value
			req.Header.Set("User-Agent", "")
		}
	}
	return &ReverseProxy{Director: director}}

NewSingleHostReverseProxy返回一個新的ReverseProxy,將URLs請求路由到targe的指定的scheme, host, base path。

// ReverseProxy is an HTTP Handler that takes an incoming request and// sends it to another server, proxying the response back to the// client.type ReverseProxy struct {
	// Director must be a function which modifies
	// the request into a new request to be sent
	// using Transport. Its response is then copied
	// back to the original client unmodified.
	// Director must not access the provided Request
	// after returning.
	Director func(*http.Request)

	Transport http.RoundTripper

	FlushInterval time.Duration

	ErrorLog *log.Logger

	BufferPool BufferPool	// ModifyResponse is an optional function that modifies the
	// Response from the backend. It is called if the backend
	// returns a response at all, with any HTTP status code.
	// If the backend is unreachable, the optional ErrorHandler is
	// called without any call to ModifyResponse.
	//
	// If ModifyResponse returns an error, ErrorHandler is called
	// with its error value. If ErrorHandler is nil, its default
	// implementation is used.
	ModifyResponse func(*http.Response) error

	ErrorHandler func(http.ResponseWriter, *http.Request, error)}

ReverseProxy類型有兩個重要的屬性,分別是DirectorModifyResponse,這兩個屬性都是函數(shù)類型,在接收到客戶端請求時,ServeHTTP函數(shù)首先調(diào)用Director函數(shù)對接受到的請求體進行修改,例如修改請求的目標地址、請求頭等;然后使用修改后的請求體發(fā)起新的請求,接收到響應后,調(diào)用ModifyResponse函數(shù)對響應進行修改,最后將修改后的響應體拷貝并響應給客戶端,這樣就實現(xiàn)了反向代理的整個流程。

NewSingleHostReverseProxy中源碼已經(jīng)對傳入的URLs進行解析并且完成了Director的修改,我們只需要調(diào)用NewSingleHostReverseProxy函數(shù)并且傳入目標服務器的URL即可,一個簡單的反向代理就完成了啦。

代碼

實例代碼只涉及微服務中 userauth模塊,可以根據(jù)實際需求自行修改部分

package mainimport (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings")type handle struct {
	host string
	port string}type Service struct {
	auth *handle
	user *handle}func (this *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var remote *url.URL	if strings.Contains(r.RequestURI, "api/auth") {
		remote, _ = url.Parse("http://" + this.auth.host + ":" + this.auth.port)
	} else if strings.Contains(r.RequestURI, "api/user") {
		remote, _ = url.Parse("http://" + this.user.host + ":" + this.user.port)
	} else {
		fmt.Fprintf(w, "404 Not Found")
		return
	}
	proxy := httputil.NewSingleHostReverseProxy(remote)
	proxy.ServeHTTP(w, r)}func startServer() {
	// 注冊被代理的服務器 (host, port)
	service := &Service{
		auth: &handle{host: "127.0.0.1", port: "8081"},
		user: &handle{host: "127.0.0.1", port: "8082"},
	}
	err := http.ListenAndServe(":8888", service)
	if err != nil {
		log.Fatalln("ListenAndServe: ", err)
	}}func main() {
	startServer()}

文章題目:Golang如何實現(xiàn)簡單的API網(wǎng)關(guān)
網(wǎng)頁URL:http://weahome.cn/article/cphgoh.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部