请注意:在使用原生Go语言的htp/net包与ajax通信时,会存在跨域问题!
原生GoWeb解决跨域问题:
//解决跨域
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
w.Header().Set("content-type", "text/json") //响应参数类型
在Go文件中设置w.header().set(string,string)。
话不多说,直接上代码!
前端html代码就是一个按钮,点击按钮,触发get请求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="button" id="getInfo" value="请求" />
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('#getInfo').click(function(){
$.ajax({
url: "http://localhost:8080/keyIndex",
data: {},
contentType: "application/json; charset=utf-8",
cache:false,
type: "get",
dataType: "text",
success: function(info) {
console.log("success!");
console.log(info)
},
error:function(res){
console.log("err:")
console.log(res)
}
});
})
});
</script>
</html>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('#getInfo').click(function(){
// ajax通常使用模板
$.ajax({
url: 路径,
data: {数据内容},
contentType: 字符集,
cache:缓存,
type: 请求方法,
dataType: 响应数据类型,
success: function(info) {
console.log("success!");
console.log(info)
},
error:function(res){
console.log("err:")
console.log(res)
}
});
})
});
</script>
Go代码:
使用goEncrypt库产生公私钥,然后 将后台产生的公私钥返回给前端的用户
package main
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
)
type PubPriKey struct {
PublicKey string `json:"publicKey"`
PrivateKey string `json:"privateKey"`
StatusCode int `json:"statusCode"`
}
// 键值对返回处理函数
func retKeyInfo(w http.ResponseWriter, r *http.Request) {
//生成公私钥文件
//goEncrypt.GetRsaKey()
keyInfo := new(PubPriKey)
publicKey, _ := ioutil.ReadFile("./public.pem")
privateKey, _ := ioutil.ReadFile("./private.pem")
keyInfo.PublicKey = string(publicKey)
keyInfo.PrivateKey = string(privateKey)
keyInfo.StatusCode = 200
data, _ := json.Marshal(keyInfo)
//解决跨域
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
w.Header().Set("content-type", "text/json") //响应参数类型
io.WriteString(w, string(data))
}
func main() {
//请求处理函数
http.HandleFunc("/keyIndex", retKeyInfo)
// 开启服务
http.ListenAndServe("127.0.0.1:8080", nil)
}