github.com/traefik/yaegi@v0.15.1/_test/cli1.go (about)

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