欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-25 18:39:44
错误写法func main() { openhttplisten()}func openhttplisten() { http.handlefunc("/", receiveclientr...

错误写法

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

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