tlama
tlama

Reputation: 617

How to buffer a response in web app in golang?

I want to make a hello world web app that will properly catch template error. So I need to buffer the response but don't know how to do it. I've put together this code. Is this the way to buffer a response in golang?

func get_handler(w http.ResponseWriter, r *http.Request) {

    buf := new(bytes.Buffer)
    err := templates.ExecuteTemplate(buf, "hello.html", nil)
    if err != nil {
        fmt.Println(err.Error())
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    w.Write([]byte(buf.String()))
}

Upvotes: 3

Views: 3967

Answers (3)

elithrar
elithrar

Reputation: 24270

You can use a bytes.Buffer "as is" by writing into it, but at the cost of discarding the buffer on every request.

Using a pooled approach (that safely resets the contents between use, but retains the buffer) can have some gains:

var bufPool *bpool.BufferPool

func YourHandler(w http.ResponseWriter, r *http.Request) {
    buf := bufPool.Get()
    defer bufPool.Put(buf)
    err := template.ExecuteTemplate(buf, "forms/create.html", user)
    // or err := json.NewEncoder(buf).Encode(value)
    if err != nil {
      return err
    }

    buf.WriteTo(w)
}

This uses the bpool library.

Upvotes: 2

SnoProblem
SnoProblem

Reputation: 1939

bytes.Buffer has a built-in method for writing out to an io.Writer:

func get_handler(w http.ResponseWriter, r *http.Request) {
    buf := new(bytes.Buffer)

    //fill buffer

    _,err := buf.WriteTo(w)
    if err != nil { 
         log.Println(err)
    }
}

docs: http://golang.org/pkg/bytes/#Buffer.WriteTo

Upvotes: 2

Ainar-G
Ainar-G

Reputation: 36239

bytes.Buffer has a Bytes method, so you don't actually need to call String and convert it to []byte:

w.Write(buf.Bytes())

Additionally, it's a good practice to write errors to stderr. Just replace your fmt with log:

if err != nil {
    log.Println(err)
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

Upvotes: 5

Related Questions