Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample code for my article
package main
import (
"fmt"
"net/http"
)
func handleNoCors(w http.ResponseWriter, req *http.Request) {
fmt.Println("Request received. Referer:", req.Header.Get("Referer"))
w.Write([]byte("Hello world!"))
}
func handleCors(w http.ResponseWriter, req *http.Request) {
fmt.Println("[/cors] Request received. Referer:", req.Header.Get("Referer"))
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "http://www.example.com")
w.Write([]byte("{\"msg\":\"success\"}"))
}
func handleCorsRedirection(w http.ResponseWriter, req *http.Request) {
fmt.Println("[/cors-redirect] Request received. Referer:", req.Header.Get("Referer"))
w.Header().Set("Access-Control-Allow-Origin", "http://www.example.com")
w.Header().Set("Location", "/cors")
w.WriteHeader(http.StatusFound)
}
func handleNoCorsRedirection(w http.ResponseWriter, req *http.Request) {
fmt.Println("[/no-cors-redirect] Request received. Referer:", req.Header.Get("Referer"))
w.Header().Set("Location", "/cors")
w.WriteHeader(http.StatusFound)
}
func main() {
http.HandleFunc("/cors", handleCors)
http.HandleFunc("/nocors", handleNoCors)
http.HandleFunc("/cors-redirect", handleCorsRedirection)
http.HandleFunc("/no-cors-redirect", handleNoCorsRedirection)
http.ListenAndServe(":3000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment