2 回答

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個贊
修正對“類型同義詞”的錯誤使用
對于數(shù)字1:
Gorilla/rpc/json的CodecRequest.WriteResponse(它實(shí)現(xiàn)Gorilla/rpc的CodecRequest)是一個位置,其中所述代碼的接觸http.ResponseWriter。
這意味著我們必須有自己的實(shí)現(xiàn)CodecRequest來設(shè)置CORS標(biāo)頭。
CodecRequest服務(wù)器使用的每一個實(shí)際上都是由Codec;生成的;Codecs是制造工廠CodecRequests,換句話說。
這意味著我們必須創(chuàng)建一個Codec來生成CodecRequest將設(shè)置CORS標(biāo)頭的。
Go的偉大之處在于,編寫這種額外的行為真的很容易!
試試這個:
package cors_codec
import (
"Gorilla/rpc"
"net/http"
"strings"
)
//interface: ain't nobody dope like me I feel so fresh and clean
func CodecWithCors([]string corsDomains, unpimped rpc.Codec) rpc.Codec {
return corsCodecRequest{corsDomains, unpimped}
}
type corsCodecRequest struct {
corsDomains []string
underlyingCodecRequest rpc.CodecRequest
}
//override exactly one method of the underlying anonymous field and delegate to it.
func (ccr corsCodecRequest) WriteResponse(w http.ResponseWriter, reply interface{}, methodErr error) error {
w.Header().add("Access-Control-Allow-Origin", strings.join(ccr.corsDomains, " "))
return ccr.underlyingCodecRequest.WriteResponse(w, reply, error)
}
type corsCodec struct {
corsDomains []string
underlyingCodec rpc.Codec
}
//override exactly one method of the underlying anonymous field and delegate to it.
func (cc corsCodec) NewRequest(req *http.Request) rpc.CodecRequest {
return corsCodecRequest{cc.corsDomains, cc.underlyingCodec.NewRequest(req)}
}
那是一個有趣的練習(xí)!
- 2 回答
- 0 關(guān)注
- 222 瀏覽
添加回答
舉報