2 回答
TA貢獻(xiàn)1824條經(jīng)驗 獲得超5個贊
您需要OPTIONS在路由器上允許方法。
https://github.com/abhimanyu1990/go-connect/blob/main/app/conf/router.configuration.go#L30
router.Handle("/api/register", c.Handler(middleware.RequestValidator(RegisterHandler, reflect.TypeOf(dto.UserRequest{})))).Methods("POST", "OPTIONS")TA貢獻(xiàn)1891條經(jīng)驗 獲得超3個贊
當(dāng)我嘗試啟用 CORS 并在 Go 中寫入標(biāo)頭時,這很煩人。最后,我創(chuàng)建了一個包裝 ResponseWriter 的結(jié)構(gòu)來檢測標(biāo)頭是否已經(jīng)寫入并且它工作正常。
package router
import (
"log"
"net/http"
)
const (
noWritten = -1
defaultStatus = http.StatusOK
)
type ResponseWriter struct {
writer http.ResponseWriter
size int
status int
}
func (w *ResponseWriter) Writer() http.ResponseWriter {
return w.writer
}
func (w *ResponseWriter) WriteHeader(code int) {
if code > 0 && w.status != code {
if w.Written() {
log.Printf("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code)
}
w.status = code
}
}
func (w *ResponseWriter) WriteHeaderNow() {
if !w.Written() {
w.size = 0
w.writer.WriteHeader(w.status)
}
}
func (w *ResponseWriter) Write(data []byte) (n int, err error) {
w.WriteHeaderNow()
n, err = w.writer.Write(data)
w.size += n
return
}
func (w *ResponseWriter) Status() int {
return w.status
}
func (w *ResponseWriter) Size() int {
return w.size
}
func (w *ResponseWriter) Written() bool {
return w.size != noWritten
}
在回應(yīng)中:
func respondJSON(w *router.ResponseWriter, status int, payload interface{}) {
res, err := json.Marshal(payload)
if err != nil {
respondError(w, internalErrorStatus.number, internalErrorStatus.description)
return
}
go w.WriteHeader(status)
header := w.Writer().Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Content-Type", "application/json")
header.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
header.Add("Access-Control-Allow-Headers", "*")
w.Write([]byte(res))
}
- 2 回答
- 0 關(guān)注
- 318 瀏覽
添加回答
舉報
