github.com/HaHadaxigua/yaegi@v1.0.1/_test/cli2.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"log"
     7  	"net"
     8  	"net/http"
     9  )
    10  
    11  type T struct {
    12  	ln net.Listener
    13  }
    14  
    15  func (t *T) Close() {
    16  	t.ln.Close()
    17  }
    18  
    19  func client(uri string) {
    20  	resp, err := http.Get(uri)
    21  	if err != nil {
    22  		log.Fatal(err)
    23  	}
    24  	body, err := io.ReadAll(resp.Body)
    25  	if err != nil {
    26  		log.Fatal(err)
    27  	}
    28  	fmt.Println(string(body))
    29  }
    30  
    31  func server(ln net.Listener, ready chan bool) {
    32  	http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
    33  		var r1 *http.Request = r
    34  		fmt.Fprintln(w, "Welcome to my website!", r1.RequestURI)
    35  	})
    36  
    37  	go http.Serve(ln, nil)
    38  	ready <- true
    39  }
    40  
    41  func main() {
    42  	ln, err := net.Listen("tcp", "localhost:0")
    43  	t := &T{ln}
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  	defer t.Close()
    48  	//	defer ln.Close()
    49  
    50  	ready := make(chan bool)
    51  	go server(ln, ready)
    52  	<-ready
    53  
    54  	client(fmt.Sprintf("http://%s/hello", ln.Addr().String()))
    55  	http.DefaultServeMux = &http.ServeMux{}
    56  }
    57  
    58  // Output:
    59  // Welcome to my website! /hello