Golang : Allow Cross-Origin Resource Sharing request
Problem:
You have a client JavaScript code that want to make XHR(XMLHttpRequest) request to another Golang server which is also controlled by you. However, on the client's browser console shows CORS (Cross-Origin Resource Sharing) error messages. How to fix the issue?
Solution:
Normally, a server should not allow XMLHttpRequest made by another unauthorized client. However, to enable Cross-Origin Resource Sharing, you will need to set the server header with Access-Control-Allow-Origin:*
to the response.
w.Header().Set("Access-Control-Allow-Origin", "*") // usually, this line is enough, but you can add the following options.
If you want to add more specific headers, these are some of the options
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control")
If you're using Nginx, Apache or Caddy as proxy instead of directly serving up from your Golang program. You can add the allow CORS and XHR headers in the proxy server configuration. For example, this tutorial shows how to do that with Caddy. (https://www.socketloop.com/tutorials/golang-setup-api-server-or-gateway-with-caddy-and-http-listenandserve-function-example)
Here you go!
package main
import (
"net/http"
"strings"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") // usually, this line is enough, but you can add the following options.
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control")
URISegments := strings.Split(r.URL.Path, "/")
if URISegments[2] != "" {
w.Write([]byte(URISegments[2]))
} else {
w.Write([]byte("You gotta give a name for me to reply...."))
}
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/replyname/", ReplyName)
http.ListenAndServe(":8080", mux)
}
See also : Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.1k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+5.3k PHP : Proper way to get UTF-8 character or string length
+18.5k Android Studio : AlertDialog and EditText to get user string input example
+6k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+7.4k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+13.5k Golang : Normalize unicode strings for comparison purpose
+11.5k Golang : How to calculate the distance between two coordinates using Haversine formula
+5.2k Golang : Create new color from command line parameters
+12.1k Golang : Convert(cast) int to int64
+7.3k Golang : Ackermann function example
+6.1k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+7k Golang : Randomize letters from a string example