SoFunction
Updated on 2025-03-03

Introduction to writing a cross-domain restful API for go native http web services

Wrong writing

func main() {
    openHttpListen()
}
func openHttpListen() {
    ("/", receiveClientRequest)
    ("go server start running...")
    err := (":9090", nil)
    if err != nil {
        ("ListenAndServe: ", err)
    }
}
func receiveClientRequest(w , r *) {
    ().Set("Access-Control-Allow-Origin", "*")             // Allow access to all domains    ().Add("Access-Control-Allow-Headers", "Content-Type") //The type of header    ().Set("content-type", "application/json")             //Return data format is json    ()
    ("Received a client request: ", )

This will still cause an error:

Say that there is no response to cross-domain header, there is no response to Access-Control-Allow-Origin in the chrome network

Correct writing:

func LDNS(w , req *) {
    if origin := ("Origin"); origin != "" {
        ().Set("Access-Control-Allow-Origin", origin)
        ().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        ().Set("Access-Control-Allow-Headers",
            "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    if  == "OPTIONS" {
        return
    }
    // Response to http code    (200)
    query := (, ".")
    value, err := (query[0])
    ("Access-Control-Allow-Origin", "*")
    if err != nil {
        (w, `{"message": ""}`)
        return
    }
    (w, value)
}

Supplement: go http allows cross-domain

1. Create middleware

import (
 "/gin-gonic/gin"
 "net/http"
)
// Cross-domain middlewarefunc Cors()  {
 return func(c *) {
  method := 
  origin := ("Origin")
  if origin != "" {
   ("Access-Control-Allow-Origin", origin)
   ("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
   ("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
   ("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
   ("Access-Control-Allow-Credentials", "false")
   ("content-type", "application/json")
  }
  if method == "OPTIONS" {
   ()
  }
  ()
 }
}

2. Reference middleware in route

router := ()
// To use "cross-domain middleware" globally before routing group, otherwise OPTIONS will return 404(Cors())

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.