Golang服务开启跨域

华泽语
2023-12-01
package httpserver

import (
	"context"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/dnsdao/dnsdao.resolver/Agent/dns"
	"github.com/dnsdao/dnsdao.resolver/config"
	"github.com/dnsdao/dnsdao.resolver/database/ldb"
	"github.com/dnsdao/dnsdao.resolver/server/httpserver/api"
	"github.com/ethereum/go-ethereum/crypto"
	"log"
	"net"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const (
	DnsName                     = "/dns/name"
	DnsEthAddress               = "/dns/ethaddr"
	DnsIP4                      = "/dns/ip4"
	DnsBlockchainAddress        = "/dns/blockchainaddr"
	DnsCName                    = "/dns/cname"
	DnsIP6                      = "/dns/ip6"
	DnsGetTotalBySubLen         = "/dns/totalbysub"
	DnsQuerySubDomainByPage     = "/dns/querysub"
	DnsGetTotalByPrice          = "/dns/totalbyprice"
	DnsAddress                  = "/dns/addr"
	GetEarningsByAddress        = "/dns/getincomebyaddr"
	GetEarningsDetailsByAddress = "/dns/getincomedetails"
	GetCashDetailsByAddress     = "/dns/getcashbyaddr"
)

func Cors(f http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")                                                            // 允许访问所有域,可以换成具体url,注意仅具体url才能带cookie信息
		w.Header().Add("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token") //header的类型
		w.Header().Add("Access-Control-Allow-Credentials", "true")                                                    //设置为true,允许ajax异步请求带cookie信息
		w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")                             //允许请求方法
		w.Header().Set("content-type", "application/json;charset=UTF-8")                                              //返回数据格式是json
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		f(w, r)
	}
}

type WebProxyServer struct {
	listenAddr string
	quit       chan struct{}
	server     *http.Server
}

type route struct {
	pattern *regexp.Regexp
	handler http.Handler
}

type RegexpHander struct {
	routes []*route
}

func (rh *RegexpHander) Handle(pattern string, handler http.Handler) {
	rh.routes = append(rh.routes, &route{pattern: regexp.MustCompilePOSIX(pattern), handler: handler})
}

func (rh *RegexpHander) HandleFunc(pattern string, handleFunc func(http.ResponseWriter, *http.Request)) {
	rh.routes = append(rh.routes, &route{pattern: regexp.MustCompilePOSIX(pattern), handler: http.HandlerFunc(handleFunc)})
}

func (rh *RegexpHander) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	for _, route := range rh.routes {
		if route.pattern.MatchString(r.URL.Path) {
			route.handler.ServeHTTP(w, r)
			return
		}
	}
	// no pattern matched; send 404 response
	http.NotFound(w, r)
}

func NewWebServer(networkAddr string) *WebProxyServer {
	ws := WebProxyServer{
		listenAddr: networkAddr,
		quit:       make(chan struct{}, 8),
	}

	return ws.init()

}

func (ws *WebProxyServer) init() *WebProxyServer {
	rh := &RegexpHander{
		routes: make([]*route, 0),
	}
	wapi := api.NewApi()
	rh.HandleFunc(DnsEthAddress, Cors(ws.ethAddrResolve))
	rh.HandleFunc(DnsName, Cors(ws.dnsNameResolve))
	//rh.HandleFunc("/tokenId", ws.DnsTokenId)
	rh.HandleFunc(DnsIP4, Cors(ws.ipv4Resolve))
	rh.HandleFunc(DnsBlockchainAddress, Cors(wapi.Blockchain))
	rh.HandleFunc(DnsCName, Cors(wapi.CName))
	rh.HandleFunc(DnsIP6, Cors(wapi.Ipv6))
	rh.HandleFunc(DnsGetTotalBySubLen, Cors(wapi.GetTotalBySubLen))
	rh.HandleFunc(DnsQuerySubDomainByPage, Cors(wapi.QuerySubDomainByPage))
	rh.HandleFunc(GetEarningsByAddress, Cors(wapi.GetEarningsByAddress))
	rh.HandleFunc(DnsAddress, Cors(wapi.AddrResolve))
	rh.HandleFunc(GetEarningsDetailsByAddress, Cors(wapi.GetEarningsDetailsByAddress))
	rh.HandleFunc(GetCashDetailsByAddress, Cors(wapi.GetCashDetailsByAddress))
	server := &http.Server{
		Handler: rh,
	}

	ws.server = server

	return ws
}
 类似资料: