3

I'm writing a server in Go, and I'm currently implementing error pages (404, 500, etc.) I have files which can be served for these errors, but if I use http.ServeFile then I get HTTP code 200 instead of the appropriate code.

Is there a way to change the status code, or do I need to rewrite http.ServeFile for this use case?

1 Answer 1

3

From reading the source I don't see any way to change the status code (other than the method failing which means you won't get your error page served). I think it's implied that if the files is served then it was an HTTP 200 which isn't entirely unreasonable.

I recommend reading the error page file into a string then using this method; https://golang.org/pkg/net/http/#Error

EDIT: That may actually not be specific enough for you even. It wants the error message as plain text so what I suggested is likely a misuse. In which case you're left with no useful abstractions to do what you want.

In response to comment, my personal preference would be something more along the line of;

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
        resp := &http.Response{
            StatusCode: 404,
        }
        resp.Write(w)
    })
}

but you could also just use w.WriteHeader(http.StatusForbidden) or whatever if that's your preference. Whatever better suites you needs. My experience would be with preparing response object in a scope different than that of the mux so for that reason I think I prefer the bit above (it makes more sense than having helper methods return unstructured data you then write in to the responsewriter).

Sign up to request clarification or add additional context in comments.

2 Comments

So you recommend using WriteHeader and io.WriteString directly?
@Charles that would be one way. Another option is to instantiate an instance of http.Response than then do resp.Write(w) and it will write the response into the ResponseWriter. That was you can explicitly set whatever values you want which is more what I was thinking of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.