牛骨文教育服务平台(让学习变的简单)
博文笔记

go 原生http web 服务跨域restful api 写法

创建时间:2017-01-11 投稿人: 浏览次数:2012

错误写法

func main() {

    openHttpListen()
}

func openHttpListen() {
    http.HandleFunc("/", receiveClientRequest)
    fmt.Println("go server start running...")

    err := http.ListenAndServe(":9090", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func receiveClientRequest(w http.ResponseWriter, r *http.Request) {

    w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
    w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
    w.Header().Set("content-type", "application/json")             //返回数据格式是json

    r.ParseForm()
    fmt.Println("收到客户端请求: ", r.Form)

这样还是会报错:

说没有得到响应跨域的头,chrome的network中确实没有响应Access-Control-Allow-Origin 

正确写法:

func LDNS(w http.ResponseWriter, req *http.Request) {

    if origin := req.Header.Get("Origin"); origin != "" {
        w.Header().Set("Access-Control-Allow-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")
    }
    if req.Method == "OPTIONS" {
        return
    }
    // 响应http code
    w.WriteHeader(200)
    query := strings.Split(req.Host, ".")
    value, err := ldns.RAMDBMgr.Get(query[0])
    fmt.Println("Access-Control-Allow-Origin", "*")
    if err != nil {
        io.WriteString(w, `{"message": ""}`)
        return
    }

    io.WriteString(w, value)
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。