package main
import (
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/go-resty/resty/v2"
)
func handleError(err error) {
if err != nil {
log.Fatalln(err)
}
}
func restyStreamDemo() {
resp, err := resty.New().R().
SetDoNotParseResponse(true).
Get("http://127.0.0.1:8000/stream")
handleError(err)
rawBody := resp.RawBody()
defer rawBody.Close()
buf := make([]byte, 1024)
for {
n, err := rawBody.Read(buf)
if n > 0 {
fmt.Print(string(buf[:n]))
}
if err == io.EOF {
break
}
handleError(err)
}
}
func baseDemo() {
req, err := http.NewRequest("GET", "http://127.0.0.1:8000/", nil)
handleError(err)
c := &http.Client{}
resp, err := c.Do(req)
handleError(err)
log.Println("Response Code:", resp.StatusCode)
body, err := io.ReadAll(resp.Body)
handleError(err)
log.Println("Response Body:", string(body))
}
func timeoutDemo() {
req, err := http.NewRequest("GET", "http://127.0.0.1:8000/timeout", nil)
handleError(err)
c := &http.Client{
Timeout: 3 * time.Second,
}
_, err = c.Do(req)
handleError(err) // will panic
}
func main() {
baseDemo()
restyStreamDemo()
timeoutDemo()
}