在golang中进行http POST的预检问题

huangapple go评论72阅读模式
英文:

Preflight issue with http POST in golang

问题

我正在使用mux包,并且有以下代码:

func saveConfig(w http.ResponseWriter, r *http.Request) {
    if origin := r.Header.Get("Origin"); origin != "" {
        w.Header().Set("Access-Control-Allow-Origin", origin)
        fmt.Println("Origin: " + origin)
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    // 如果是预检请求(Preflighted OPTIONS request),则直接返回
    if r.Method == "OPTIONS" {
        return
    }

    body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
    if err != nil {
        fmt.Println("Error: %s\n", err)
        w.WriteHeader(http.StatusInternalServerError)
        return
    }

    fmt.Println("JSON body:" + string(body))
    if err := r.Body.Close(); err != nil {
        panic(err)
    }

    w.WriteHeader(http.StatusCreated)
}

在IE上运行良好,但是Chrome发送了一个OPTIONS方法的预检请求,我收到了404的响应。非常感谢任何帮助。

英文:

I am using mux package and have this code:

func saveConfig(w http.ResponseWriter, r *http.Request) {
	if origin := r.Header.Get("Origin"); origin != "" {
		w.Header().Set("Access-Control-Allow-Origin", origin)
		fmt.Println("Origin: " + origin)
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
	}
	// Stop here if its Preflighted OPTIONS request
	if r.Method == "OPTIONS" {
		return
	}

	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		fmt.Println("Error: %s\n", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	fmt.Println("JSON body:" + string(body))
	if err := r.Body.Close(); err != nil {
		panic(err)
	}

	w.WriteHeader(http.StatusCreated)
}

It's working fine on IE but chrome preflight is sending an OPTIONS method and I am getting 404 response back. Any help would be greatly appreciated.

答案1

得分: 1

代码注册了POST方法,但没有注册OPTIONS方法。一种方法是将代码更改为以下内容:

func NewRouter() *mux.Router { 
    router := mux.NewRouter().StrictSlash(true) 
    for _, route := range routes { 
        var handler http.Handler 
        handler = route.HandlerFunc
        handler = commonlibrary.Logger(handler, route.Name) 
        return router.Methods(route.Method, "OPTIONS").Path(route.Pattern).Name(route.Name).Handler(handler)
    }
}

这将为所有处理程序添加OPTIONS方法。另一种方法是将Route的Method字段更改为Methods []string,并创建路由器如下:

return router.Methods(route.Methods..., "OPTIONS").Path(route.Pattern).Name(route.Name).Handler(handler)

这将允许您将OPTIONS方法添加到一部分处理程序中。

还有一种方法是为OPTIONS注册一个单独的处理程序:

Route{"saveConfig", "OPTIONS", "/saveConfig", preflight}
英文:

The code registers for POST, but not OPTIONS. One approach is to change your code to the following:

func NewRouter() *mux.Router { 
    router := mux.NewRouter().StrictSlash(true) 
    for _, route := range routes { 
        var handler http.Handler 
        handler = route.HandlerFunc
        handler = commonlibrary.Logger(handler, route.Name) 
        return router.Methods(route.Method, "OPTIONS").Path(route.Pattern).Name(route.Name).Handler(handler)
 }

This will add OPTIONS to all handlers. Another approach is to change the Route Method field to Methods []string and create the router as:

return router.Methods(route.Methods..., "OPTIONS").Path(route.Pattern).Name(route.Name).Handler(handler)

This will allow you to add OPTIONS to a subset of the handlers.

Yet another approach is to register a separate handler for OPTIONS:

 Route{"saveConfig", "OPTIONS", "/saveConfig", preflight}

huangapple
  • 本文由 发表于 2015年7月15日 00:36:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/31412478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定