为了账号安全,请及时绑定邮箱和手机立即绑定

从 go-swagger UI 访问 API 时 Golang 中的 CORS 问题

从 go-swagger UI 访问 API 时 Golang 中的 CORS 问题

Go
犯罪嫌疑人X 2022-07-11 10:47:38
我已经为我的 API 文档实现了 go-swagger,该文档在我的本地主机上的不同端口上运行,我的应用程序在端口 8888 上运行。我已经实现了 cors https://github.com/rs/cors我实现 cors 的代码是var Router = func() *mux.Router{    router := mux.NewRouter()    var c = cors.New(cors.Options{        AllowedOrigins: []string{"*"},        AllowCredentials: true,        AllowedMethods :[]string{"POST", "PUT","GET","DELETE","OPTIONS"},        AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},        MaxAge: 300,        // Enable Debugging for testing, consider disabling in production        Debug: true,    })    RegisterHandler := http.HandlerFunc(controllers.Register)    router.Handle("/api/register",c.Handler(middleware.RequestValidator(RegisterHandler,reflect.TypeOf(dto.UserRequest{})))).Methods("POST")    fmt.Println("var1 = ", reflect.TypeOf(router))     return router}当从 Postman 发出请求时,似乎代码运行良好邮递员响应标头access-control-allow-credentials →trueaccess-control-allow-origin →*content-length →123content-type →application/jsondate →Wed, 14 Oct 2020 04:02:37 GMTvary →Origin 由于我在实现我的控制台上打印的 cors 中间件日志时启用了调试,如下所示控制台日志[cors] 2020/10/14 09:32:37 Handler: Actual request[cors] 2020/10/14 09:32:37   Actual response added headers: map[Access-Control-Allow-Credentials:[true] Access-Control-Allow-Origin:[*] Vary:[Origin]]问题当我在浏览器中从 Swagger-UI 访问相同的 API 时,我遇到了未设置“Access-Control-Allow-Origin”标头的问题Access to fetch at 'http://localhost:8888/api/register' from origin 'http://localhost:45601' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.并且控制台上没有打印日志。从 Swagger UI 访问 API 时,似乎无法访问 cors 中间件代码。这是 swagger 响应的 Bowser 网络调用详细信息
查看完整描述

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")



查看完整回答
反对 回复 2022-07-11
?
万千封印

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))

}


查看完整回答
反对 回复 2022-07-11
  • 2 回答
  • 0 关注
  • 253 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信