🪴 notes

Search

Search IconIcon to open search

cors in go

Published Aug 19, 2023 Last updated Nov 25, 2023 Edit Source

src

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func enableCors(w *http.ResponseWriter) {   
	(*w).Header().Set("Access-Control-Allow-Origin", "*")   
}

func handleArticles(w http.ResponseWriter, r *http.Request) {
	enableCors(&w)
	js, err := json.Marshal(Articles)   
	if err != nil {   
		http.Error(w, err.Error(), http.StatusInternalServerError)   
		return   
	}
	w.Header().Set("Content-Type", "application/json")   
	w.Write(js)   
}

with websockets using gorilla/websocket

1
2
3
4
5
6
var upgrader = websocket.Upgrader{
	Subprotocols: []string{"echo"},
    CheckOrigin: func (r *http.Request) bool  {
        return true
    },
}

both allows all. (modify for prod)