Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you return json in golang http.Error?

Tags:

go

Can you return json when http.Error is called?

        myObj := MyObj{
            MyVar: myVar}

        data, err := json.Marshal(myObj)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return 
        }
        w.Write(data)
        w.Header().Set("Content-Type", "application/json")

        http.Error(w, "some error happened", http.StatusInternalServerError)

I see that it returns 200 with no json but the json is embed in text

like image 1000
user10714010 Avatar asked Nov 29 '22 21:11

user10714010


1 Answers

I've discovered that it's really easy to read the Go source. If you click on the function in the docs, you will be taken to the source for the Error function: https://golang.org/src/net/http/server.go?s=61907:61959#L2006

// Error replies to the request with the specified error message and HTTP code.
// It does not otherwise end the request; the caller should ensure no further
// writes are done to w.
// The error message should be plain text.
func Error(w ResponseWriter, error string, code int) {
    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.WriteHeader(code)
    fmt.Fprintln(w, error)
}

So if you want to return JSON, it's easy enough to write your own Error function.

func JSONError(w http.ResponseWriter, err interface{}, code int) {
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.WriteHeader(code)
    json.NewEncoder(w).Encode(err)
}
like image 147
craigmj Avatar answered Dec 21 '22 23:12

craigmj