From f03b73f27ee6efc3354719171212e6ccf1fa9c7c Mon Sep 17 00:00:00 2001 From: hackerchai Date: Thu, 5 Sep 2024 18:06:50 +0800 Subject: [PATCH] refactor(x/net/ht tp/demo): Use echo read demo Signed-off-by: hackerchai --- x/net/http/_demo/http.go | 49 ++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/x/net/http/_demo/http.go b/x/net/http/_demo/http.go index 2b20f0b..31a3d14 100644 --- a/x/net/http/_demo/http.go +++ b/x/net/http/_demo/http.go @@ -2,36 +2,13 @@ package main import ( "fmt" - //"io" + "io" "github.com/goplus/llgo/x/net/http" ) func echoHandler(w http.ResponseWriter, r *http.Request) { fmt.Printf("echoHandler called\n") - //TODO(hackerchai): read body and echo - // fmt.Printf("> %s %s HTTP/%d.%d\n", r.Method, r.RequestURI, r.ProtoMajor, r.ProtoMinor) - // for key, values := range r.Header { - // for _, value := range values { - // fmt.Printf("> %s: %s\n", key, value) - // } - // } - // fmt.Printf("URL: %s\n", r.URL.String()) - // // fmt.Println("ContentLength: %d", r.ContentLength) - // // fmt.Println("TransferEncoding: %s", r.TransferEncoding) - // //TODO: read body and echo - // body, err := io.ReadAll(r.Body) - // println("body read") - - // if err != nil { - // http.Error(w, "Error reading request body", http.StatusInternalServerError) - // return - // } - // defer r.Body.Close() - // fmt.Printf("body read") - // w.Header().Set("Content-Type", "text/plain") - // w.Write(body) - fmt.Printf("> %s %s HTTP/%d.%d\n", r.Method, r.RequestURI, r.ProtoMajor, r.ProtoMinor) for key, values := range r.Header { for _, value := range values { @@ -39,8 +16,30 @@ func echoHandler(w http.ResponseWriter, r *http.Request) { } } fmt.Printf("URL: %s\n", r.URL.String()) + fmt.Printf("RemoteAddr: %s\n", r.RemoteAddr) + // fmt.Println("ContentLength: %d", r.ContentLength) + // fmt.Println("TransferEncoding: %s", r.TransferEncoding) + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "Error reading request body", http.StatusInternalServerError) + return + } + + defer r.Body.Close() + fmt.Printf("body read") w.Header().Set("Content-Type", "text/plain") - w.Write([]byte("hello world\n")) + w.Write(body) + + // fmt.Printf("> %s %s HTTP/%d.%d\n", r.Method, r.RequestURI, r.ProtoMajor, r.ProtoMinor) + // for key, values := range r.Header { + // for _, value := range values { + // fmt.Printf("> %s: %s\n", key, value) + // } + // } + // fmt.Printf("URL: %s\n", r.URL.String()) + // fmt.Printf("RemoteAddr: %s\n", r.RemoteAddr) + // w.Header().Set("Content-Type", "text/plain") + // w.Write([]byte("hello world\n")) } func main() {