华域联盟 Golang go 原生http web 服务跨域restful api的写法介绍

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

错误写法

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)
}

补充:go http允许跨域

1.创建中间件

import (
 "github.com/gin-gonic/gin"
 "net/http"
)
// 跨域中间件
func Cors() gin.HandlerFunc {
 return func(c *gin.Context) {
  method := c.Request.Method
  origin := c.Request.Header.Get("Origin")
  if origin != "" {
   c.Header("Access-Control-Allow-Origin", origin)
   c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
   c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
   c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
   c.Header("Access-Control-Allow-Credentials", "false")
   c.Set("content-type", "application/json")
  }
  if method == "OPTIONS" {
   c.AbortWithStatus(http.StatusNoContent)
  }
  c.Next()
 }
}

2.在route中引用中间件

router := gin.Default()
// 要在路由组之前全局使用「跨域中间件」, 否则OPTIONS会返回404
router.Use(Cors())

以上为个人经验,希望能给大家一个参考,也希望大家多多支持华域联盟。如有错误或未考虑完全的地方,望不吝赐教。

本文由 华域联盟 原创撰写:华域联盟 » go 原生http web 服务跨域restful api的写法介绍

转载请保留出处和原文链接:https://www.cnhackhy.com/111214.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

Mac GoLand打不开(闪退)也不报错的解决方案

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们