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

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。