当前位置 博文首页 > golang实现跨域访问的方法

    golang实现跨域访问的方法

    作者:benben_2015 时间:2021-07-07 17:42

    前端通过Ajax来获取服务器资源时,会存在跨域问题。因为Ajax只能同源使用(预防某些恶意行为),所以当访问不在同一个域中的资源时,就会出现跨域限制。尤其在开发和测试时,跨域问题会给前端测试带来非常不便。

    不过CORS(Cross-Origin Resource Sharing,跨域资源共享)解决了这个问题,它背后的基本思想是:使用自定义的HTTP头部让浏览器与服务器进行沟通,从而决定请求或响应是否应该成功。CORS需要浏览器和服务器同时支持。整个CORS通信过程,浏览器是自动完成,而服务器需要手动配置。

    ajax.html

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport"
         content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <script>
        function loadXMLDoc() {
          var xmlhttp;
          if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
          }
          else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          }
          xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
              document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            }
          }
          xmlhttp.open("GET", "http://127.0.0.1:8000/ajax", true);
          xmlhttp.send();
        }
      </script>
      <title>Document</title>
    </head>
    <body>
      <h2>cross origin</h2>
      <button type="button" onclick="loadXMLDoc()">请求数据</button>
      <div ></div>
    </body>
    </html>

    crossorigin.go

    package main
    
    import (
      "net/http"
      "html/template"
      "fmt"
      "encoding/json"
    )
    
    type Message struct {
      Name string `json:"name"`
      Msg string `json:"msg"`
    }
    
    func main() {
      http.HandleFunc("/", Entrance)
      http.HandleFunc("/ajax", TestCrossOrigin)
      http.ListenAndServe(":8000", nil)
    }
    
    func Entrance(w http.ResponseWriter, r *http.Request) {
      t,_:=template.ParseFiles("templates/ajax.html")
      t.Execute(w, nil)
    }
    
    func TestCrossOrigin(w http.ResponseWriter, r *http.Request) {
      if r.Method == "GET" {
        var message Message
        message.Name = "benben_2015"
        message.Msg = "success"
    
        result, err := json.Marshal(message)
        if err != nil {
          fmt.Println(err)
          return
        }
        ResponseWithOrigin(w, r, http.StatusOK, result)
        return
      }
    }
    func ResponseWithOrigin(w http.ResponseWriter, r *http.Request, code int, json []byte) {
      w.Header().Set("Content-Type", "application/json; charset=utf-8")
      w.WriteHeader(code)
      w.Write(json)
    }

    当从 http://localhost:8000/ 页面(ajax.html)通过ajax访问 http://localhost:8000/ajax 时,就会出现下图所示的错误:

     

    解决方法: golang设置HTTP头部相当简单,标准包有现成的方法可以使用。只要在服务器端的响应头中添加下面一句代码就可以正常访问了。

    w.Header().Set("Access-Control-Allow-Origin", "*")
    //"*"表示接受任意域名的请求,这个值也可以根据自己需要,设置成不同域名
    jsjbwy
下一篇:没有了