Skip to content

Instantly share code, notes, and snippets.

@adityathebe
Last active January 4, 2023 15:20
Show Gist options
  • Save adityathebe/f5905b9e28bbc78ba2abbd69e88a5c0d to your computer and use it in GitHub Desktop.
Save adityathebe/f5905b9e28bbc78ba2abbd69e88a5c0d to your computer and use it in GitHub Desktop.
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