1

I read this solution for resolve body data from a proxy. Golang: how to read response body of ReverseProxy?

But I cannot read the body as a plain string, maybe the encoding is not right or other cryption.

My question is how to encode or transform the body to readable html string?

Currently I get:

n8�������♠�♠�A��b:J���g>-��ˤ���[���.....

Code example:

 reverseProxy := httputil.NewSingleHostReverseProxy(url)
reverseProxy.ModifyResponse = func (resp *http.Response) (err error) {
                var contentType = resp.Header.Get("Content-Type")

                if strings.HasPrefix(contentType, "text/html") {
                    b, err := ioutil.ReadAll(resp.Body) //Read html
                    if err != nil {
                        return  err
                    }
                    err = resp.Body.Close()
                    if err != nil {
                        return err
                    }

                    body := ioutil.NopCloser(bytes.NewReader(b))
                    resp.Body = body
                    resp.ContentLength = int64(len(b))

                    log.Printf(string(b))

                }

                return nil
            }
  • 3
    Looks like the server is lying about the content-type. Is there a content-encoding or transfer-encoding header? What does [DetectContentType](https://golang.org/pkg/net/http/#DetectContentType) return? – Peter May 12 '21 at 11:19
  • 3
    Note that `strings.HasPrefix(contentType, "text/html")` is the WRONG way to check a content type. Your content type might be `text/htmlolthisisreallybinary`. Use [`mime.ParseMediaType`](https://golang.org/pkg/mime/#ParseMediaType) instead. – Jonathan Hall May 12 '21 at 11:54
  • Thanks your both. I know what you mean, @Flimzy but it don't look like the problem. With the ParseMediaType I still get text/html the full content type are text/html; charset=UTF-8 The Proxy behind that are custom php application Thanks Peter for your help. I get this as detected content type test content text/html; charset=UTF-8 ts text/html 2021/05/20 10:58:19 detect type application/x-gzip This should be the reason why I only get unreadable body – Darius Sobczak May 20 '21 at 11:00

0 Answers0