Avatar ·

How to set HTTP headers in Go (CORS, Content-Type and others)

Hello everyone! I'm a beginner Go developer and I'm writing my first REST API using net/http. I ran into a problem: my frontend (React, running on localhost:3000) cannot send requests to the server (localhost:8080) due to CORS. I'm trying to set headers manually, but something is going wrong. Here's my code: ```go package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `{"message": "Hello"}`) } func main() { http.HandleFunc("/api", handler) http.ListenAndServe(":8080", nil) } ``` The problem is that when I make a POST request with a JSON body, the browser still gives a CORS error. I tried d