Set http headers for multiple handlers in go

go

Solution

I'm not sure about the multiple handlers thing, but I do know why the code you wrote is failing. The key is that the line:

*wr.Header().Set("Content-Type", "application/json")

is being interpreted, because of operator precedence, as:

*(wr.Header().Set("Content-Type", "application/json"))

Since `wr` has the type `*http.ResponseWriter`, which is a pointer to and interface, rather than the interface itself, this won't work. I assume that you knew that, which is why you did `*wr`. I assume what you meant to imply to the compiler is:

(*wr).Header().Set("Content-Type", "application/json")

If I'm not mistaken, that should compile and behave properly.

Problem

I'm trying to set an http header for multiple handlers. My first thought was to make a custom write function that would set the header before writing the response like the code sample at the bottom. However, when I pass a pointer to the http.ResponseWriter and try to access it from my function it tells me that "type *http.ResponseWriter has no Header method". What is the best way to set headers for multiple handlers, and also why isn't the pointer working the way I want it to? ``` func HelloServer(w http.ResponseWriter, req *http.Request) { type Message struct { Name string Body string Time int64 } m := Message{"Alice", "Hello", 1294706395881547000} b, _ := json.Marshal(m) WriteJSON(&w, b) } func WriteJSON(wr *http.ResponseWriter, rawJSON []byte) { *wr.Header().Set("Content-Type", "application/json") io.WriteString(*wr, string(rawJSON)) } func main() { http.HandleFunc("/json", HelloServer) err := http.ListenAndServe(":9000", nil) if err != nil { log.Fatal("ListenAndServer: ", err) } } ```

Original source