SoFunction
Updated on 2025-03-05

How to read the content of a body in Golang language

Golang reads body content

I won’t go into words anymore, just post the code. I don’t know why it’s so complicated. Is it because I’m worried that the body content cannot be fully accepted at once, so I set up an interface to read the content?

import (
	...
	"io/ioutil"
	...
)

...

func myPost(w , r *) {
	s, _ := () //Read the body content into the string s	(w, "%s", s)        //Show content in the return page.}

...

Golang Reuse

For requests other than Get

package main

import (
    "net/http"
    "strings"
    )

func main(){
        reader := ("hello")
        req,_ := ("POST","",reader)
        client := {}
        (req) // The first time the request will be successful        (req) // Request failed}

The second request will make an error

http: ContentLength=5 with Body length 0

The reason is that the end position has been read after the first request, so the body cannot be read during the second request.

Solution:

Redefine a ReadCloser implementation class replacement

package reader

import (
    "io"
    "net/http"
    "strings"
    "sync/atomic"
)

type Repeat struct{
    reader 
    offset int64
}

// Read rewrites the reading method so that you can read from the specified location every time you read itfunc (p *Repeat) Read(val []byte) (n int, err error) {
    n, err = (val, )
    atomic.AddInt64(&, int64(n))
    return
}

// Reset reset offsetfunc (p *Repeat) Reset(){
        atomic.StoreInt64(&,0)
}

func (p *Repeat) Close() error {
    // Because the readcloser interface is implemented, the close method needs to be implemented    // But the value in repeat is likely to be read-only, so here is just trying to close it.    if  != nil {
            if rc, ok := .(); ok {
                return ()
            }
        }
    return nil
}

func doPost()  {
    client := {}
    reader := ("hello")
    req , _ := ("POST","",reader)
     = &Repeat{reader:reader,offset:0}
    (req)
    // Reset offset to 0    .(*Repeat).Reset()
    (req)
}

This way, there will be no errors, because the Close() method has also been rewritten, so it also solves the problem of automatic closing when request is reused.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.