Enable CORS in Golang
Solution 1
I use gorilla/mux
package to build Go RESTful API server, and client use JavaScript Request can work,
My Go Server runs at localhost:9091
, and the Server code:
router := mux.NewRouter()
//api route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeopleAPI).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))
I find giving OPTIONS
here is important, otherwise error will occur:
OPTIONS http://localhost:9091/people 405 (Method Not Allowed)
Failed to load http://localhost:9091/people: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9092' is therefore not allowed access. The response had HTTP status code 405.
after allow OPTIONS
it works great. I get the idea from This Article.
Besides, MDN CORS doc mention:
Additionally, for HTTP request methods that can cause side-effects on server's data, the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.
Following is the api GetPeopleAPI method, note in the method I give comment //Allow CORS here By * or specific origin, I have another similar answer explaining the concept of CORS Here:
func GetPeopleAPI(w http.ResponseWriter, r *http.Request) {
//Allow CORS here By * or specific origin
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// return "OKOK"
json.NewEncoder(w).Encode("OKOK")
}
In the client, I use html with javascript on localhost:9092
, and javascript will send request to server from localhost:9092
function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
} catch (error) {
alert(error.message);
}
}
and the request can successfully get response "OKOK"
.
You can also check response/request header information by tools like Fiddler
.
Solution 2
Thanks for the clue - it's all in the header! I use only these golang headers on the server side:
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
Now works with this JQuery:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$.ajax({
type: 'GET',
url: 'https://www.XXXXXXX.org/QueryUserID?u=juXXXXny&p=blXXXXXne',
crossDomain: true,
dataType: 'text',
success: function(responseData, textStatus, jqXHR) {
alert(responseData);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
</script>
Solution 3
You can check this out https://github.com/rs/cors
This would handle the Options
Request as well
Solution 4
For allowing CORS your server should to catch all Preflight request that's browser sends before real query with OPTIONS method to the same path.
First way is managing this manually by something like this:
func setupCORS(w *http.ResponseWriter, req *http.Request) {
(*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")
}
func indexHandler(w http.ResponseWriter, req *http.Request) {
setupCORS(&w, req)
if (*req).Method == "OPTIONS" {
return
}
// process the request...
}
The second way is use ready to third party pkg like https://github.com/rs/cors
package main
import (
"net/http"
"github.com/rs/cors"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"hello\": \"world\"}"))
})
// cors.AllowAll() setup the middleware with default options being
// all origins accepted with simple methods (GET, POST). See
// documentation below for more options.
handler := cors.AllowAll().Handler(mux)
http.ListenAndServe(":8080", handler)
}
Solution 5
GO SERVER SETTING :
package main
import (
"net/http"
)
func Cors(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=ascii")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers","Content-Type,access-control-allow-origin, access-control-allow-headers")
w.Write([]byte("Hello, World!"))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/plm/cors",Cors)
http.ListenAndServe(":8081", mux)
}
Client JQUERY AJAX SETTING :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<br> Please confirm to proceed : <button class="myConfirmButton1">Go!!</button>
<div id="loader1" style="display:none;">loading...</div>
<div id="loader2" style="display:none;">...done</div>
<div id="myFeedback1"></div>
<script>
$(document).ready(function(){
$(".myConfirmButton1").click(function(){
$('#loader1').show();
$.ajax({
url:"http://[webserver.domain.com:8081]/plm/cors",
dataType:'html',
headers: {"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "access-control-allow-origin, access-control-allow-headers"},
type:'get',
contentType: 'application/x-www-form-urlencoded',
success: function( data, textStatus, jQxhr ){
$('#loader1').hide();
$('#loader2').show();
$('#myFeedback1').html( data );
},
error: function( jqXhr, textStatus, errorThrown ){
$('#loader1').hide();
$('#myFeedback1').html( errorThrown );
alert("error" + errorThrown);
}
});
});
});
</script>
</body>
Client TEST REQUEST with curl and obtained response :
curl -iXGET http://[webserver.domain.com:8081]/plm/cors
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Content-Type,access-control-allow-origin, access-control-allow-headers
Access-Control-Allow-Origin: *
Content-Type: text/html; charset=ascii
Date: Wed, 17 Jan 2018 13:28:28 GMT
Content-Length: 13
Hello, World!
![Yash Srivastava](https://i.stack.imgur.com/C6dJs.jpg?s=256&g=1)
Yash Srivastava
Updated on February 05, 2022Comments
-
Yash Srivastava over 2 years
Hi I'm implementing rest apis and for that I want to allow cross origin requests to be served.
What I am currently doing:
Go-server code on AWS:
func (c *UserController) Login(w http.ResponseWriter, r *http.Request, ctx *rack.Context) { w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin")) w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") ... ... c.render.Json(w,rsp, http.StatusOK) return }
Ajax code on localhost:
<script> $( document ).ready(function() { console.log( "ready!" ); $.ajax({ url: 'http://ip:8080/login', crossDomain: true, //set as a cross domain requests withCredentials:false, type: 'post', success: function (data) { alert("Data " + data); }, }); });
I am getting the following error on browser console: XMLHttpRequest cannot load http://ip:8080/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access. The response had HTTP status code 422.
I tried adding preflight options:
func corsRoute(app *app.App) { allowedHeaders := "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization,X-CSRF-Token" f := func(w http.ResponseWriter, r *http.Request) { if origin := r.Header.Get("Origin"); origin != "" { 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", allowedHeaders) w.Header().Set("Access-Control-Expose-Headers", "Authorization") } return } app.Router.Options("/*p", f, publicRouteConstraint) }
But it is not working.
What can be done to fix it.
-
Mawardy over 4 yearsto add multiple Access-Control-Allow-Headers use comma separated list like : w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Accept")
-
Cavdy over 4 yearsThis should be marked as the best answer... It is very useful... It solved my issue
-
V. Dalechyn over 4 yearsit's a bad practice to allow CORS *
-
B.Z. almost 4 yearsYes, it's important to have the OPTIONS check since CORS check uses OPTIONS. If HTTP request OPTIONS failed, it would fail the CORS too.
-
alex over 2 years@V.Dalechyn oh yeah - so then what's the "right" way if you have a public api that people can use?
-
V. Dalechyn over 2 years@alex Did anyone mention that the route is public to call from any origin? If Author tries to make ajax requests out of the browser locally he has to do it through proxy to fool his browser. CORS has to allow only specified origins or someone can post a request from a phishing site, retrieve JWT and proceed with money withdrawal for example
-
alex over 2 years@V.Dalechyn not in this case - but stating "it's bad practice" doesn't cover all use cases.
-
V. Dalechyn over 2 years@alex why not in this case? OP is implementing login controller and triggers fetch with ajax on html page inside <script></script>.
-
Jordan Mitchell Barrett about 2 yearsNote that you need to set these headers before writing to
w
.