davecgh / go-spew

Implements a deep pretty printer for Go data structures to aid in debugging
ISC License
5.97k stars 361 forks source link

Suggested example for use in web application debugging #33

Closed jbuberel closed 9 years ago

jbuberel commented 9 years ago

I thought it might be useful to add the following snippet to the README file to help users get started with the library:

package main

import (
    "fmt"
    "net/http"

    "github.com/davecgh/go-spew/spew"

)

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:])
    fmt.Fprintf(w, "<!--\n" + spew.Sdump(w) + "\n-->")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

If you're OK with something like this, I'll send a pull request.

dmitshur commented 9 years ago

I'd like to point out an issue with the code you posted.

fmt.Fprintf(w, "<!--\n" + spew.Sdump(w) + "\n-->")

This is unsafe. You're inserting plain text into HTML without escaping it. It's possible one of the values being dumped may contain the string sequence --> which will cause the HTML comment block to end and create possible HTML errors, etc.

That problem can be fixed by escaping the string into HTML. Go has such functionality available in standard library, so it's trivial to do:

fmt.Fprintf(w, "<!--\n" + html.EscapeString(spew.Sdump(w)) + "\n-->")

See https://godoc.org/html#EscapeString.

davecgh commented 9 years ago

Sure, I'll accept a pull request for it. However, as @shurcooL pointed out, please ensure you escape the HTML to avoid having an example that would permit malicious use.

jbuberel commented 9 years ago

https://github.com/davecgh/go-spew/pull/34