2 回答
TA贡献1824条经验 获得超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贡献1891条经验 获得超3个赞
当我尝试启用 CORS 并在 Go 中写入标头时,这很烦人。最后,我创建了一个包装 ResponseWriter 的结构来检测标头是否已经写入并且它工作正常。
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
}
在回应中:
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 关注
- 253 浏览
添加回答
举报