Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving Static Files with a HTTP 500 Status

Tags:

go

Is there a way to serve static files over HTTP in Go with a custom status code (without re-writing a significant amount of private code)?

From what I can see:

  1. http.ServeFile calls the helper function http.serveFile
  2. It then calls http.ServeContent after determining the mod time and size of the file/dir (and if it exists)
  3. Finally, http.serveContent is called, which sets the correct headers (Content-Type, Content-Length) and sets a http.StatusOK header here.

I think I already know the answer for this, but if someone has an alternative solution it'd be useful.

The use case is serving 500.html, 404.html, et. al files. I'd normally use nginx to catch Go's usual plain http.Error responses and have nginx serve the file off disk, but I'm in an environment where that's not an option.

like image 956
elithrar Avatar asked Mar 16 '23 16:03

elithrar


1 Answers

Wrap http.ResponseWriter:

type MyResponseWriter struct {
    http.ResponseWriter
    code int
}

func (m MyResponseWriter) WriteHeader(int) {
    m.ResponseWriter.WriteHeader(m.code)
}

And then (for an HTTP 500):

http.ServeFile(MyResponseWriter{rw, 500}, rq, "file.name")

Where rw is the "actual" http.ResponseWriter and rq is the *http.Request object.

like image 80
thwd Avatar answered Mar 30 '23 21:03

thwd