golang下一些跨域问题的处理
【摘要】 GET跨域处理gmux.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域 w.Header().Add("Access-Control-Allow...
GET跨域处理
gmux.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域 w.Header().Add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type,Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token, content-type") //header的类型 w.Header().Set("content-type", "application/json") //返回数据格式是json w.Header().Add("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, POST, DELETE, OPTIONS"); fmt.Fprint(w, "{\"version\":\"v1.2\"}") }).Methods("GET")
POST情况下的处理使用axios时需要注意OPTIONS请求的情况
gmux.HandleFunc("/xxx", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type,Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token, content-type") w.Header().Set("content-type", "application/json") w.Header().Add("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, POST, DELETE, OPTIONS"); if r.Method == "OPTIONS" { return } if r.Header.Get("Content-Type") != "" { value, _ := header.ParseValueAndParams(r.Header, "Content-Type") if value != "application/json" { msg := "Content-Type header is not application/json" http.Error(w, msg, http.StatusUnsupportedMediaType) return } } r.Body = http.MaxBytesReader(w, r.Body, 1048576) b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { fmt.Println("b is null"); http.Error(w, err.Error(), 500) return } //var data ExecBat //err = json.Unmarshal(b, &data) //if err != nil { // fmt.Println("json.Unmarshal"); // http.Error(w, err.Error(), 500) // return //} //code, err := base64.StdEncoding.DecodeString(data.Code) //if err != nil { // fmt.Fprint(w,"error:", err) //} ... }).Methods("POST","OPTIONS")
静态文件的处理
dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { fmt.Println(err) } gmux.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir+"\\static")))) gmux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, dir+"\\index.html") }).Methods("GET")
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)