Description of go native HTTP web service cross domain restful API

Time:2021-12-4

Wrong writing

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", "*") // allow access to all domains
    w. Header(). Add ("access control allow headers", "content type") // type of header
    w. Header(). Set ("content type", "application / JSON") // the returned data format is JSON
    r.ParseForm()
    FMT. Println ("received client request:", r.form)

This will still report an error:

It is said that there is no response cross domain header, and there is no response access control allow origin in Chrome’s network

Correct writing:

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

Supplement: go HTTP allows cross domain

1. Create Middleware

import (
 "github.com/gin-gonic/gin"
 "net/http"
)
//Cross domain Middleware
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. Reference Middleware in route

router := gin.Default()
//To use cross domain middleware globally before routing groups, otherwise options will return 404
router.Use(Cors())

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.