I'm implementing REST API's in Go and for that I want to allow cross origin requests to be served.
What I am currently doing:
Go server code:
//handleCrossO ... This function will handle CROS
func handleCrossO(w *http.ResponseWriter) {
(*w).Header().Set("Content-Type", "application/json")
(*w).Header().Set("Access-Control-Allow-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, Auth")
}
//Response ... This function will create response
func Response(w http.ResponseWriter, message string, statusCode int)
{
handleCrossO(&w)
w.WriteHeader(statusCode)
w.Write([]byte("{\"message\":\"" + message + "\"}"))
}
I am getting the following error on browser console:
Access to XMLHttpRequest at 'http://ip:8080/config' from origin 'http://ip:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have also tried the following code to check OPTIONS method:
// CheckAuthorization function check if the User is autrhorized to make calls or not
// if ssid is mising then give unauthorized error otherwise call next
func CheckAuthorization(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
//handle preflight in here
response.Response(w, "success", 200)
}else {
store := session.SessionStore()
session, _ := store.Get(r, utils.SessionName)
ssid := r.Header.Get("Auth")
if _, ok := session.Values[ssid]; ok {
next.ServeHTTP(w, r)
} else {
var getTokenRes = GetTokenRes{}
sendResponse(w, getTokenRes, 1, "Invalid
SSID", 400)
}
}
}
}
But it is not working.
I have also tried allow OPTIONS method:
router.HandleFunc("/network", authmiddleware.CheckAuthorization(createConfiguration)).Methods("POST", "OPTIONS")