tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/net/http-get/main.go (about)

     1  // This example gets an URL using http.Get().  URL scheme can be http or https.
     2  //
     3  // Note: It may be necessary to increase the stack size when using "net/http".
     4  // Use the -stack-size=4KB command line option.
     5  //
     6  // Some targets (Arduino Nano33 IoT) don't have enough SRAM to run http.Get().
     7  // Use the following for those targets:
     8  //
     9  //     examples/net/webclient (for HTTP)
    10  //     examples/net/tlsclient (for HTTPS)
    11  
    12  //go:build ninafw || wioterminal
    13  
    14  package main
    15  
    16  import (
    17  	"fmt"
    18  	"io"
    19  	"log"
    20  	"machine"
    21  	"net/http"
    22  	"net/url"
    23  	"strings"
    24  	"time"
    25  
    26  	"tinygo.org/x/drivers/netlink"
    27  	"tinygo.org/x/drivers/netlink/probe"
    28  )
    29  
    30  var (
    31  	ssid string
    32  	pass string
    33  )
    34  
    35  func main() {
    36  
    37  	waitSerial()
    38  
    39  	link, _ := probe.Probe()
    40  
    41  	err := link.NetConnect(&netlink.ConnectParams{
    42  		Ssid:       ssid,
    43  		Passphrase: pass,
    44  	})
    45  	if err != nil {
    46  		log.Fatal(err)
    47  	}
    48  
    49  	name := "John Doe"
    50  	occupation := "gardener"
    51  
    52  	params := "name=" + url.QueryEscape(name) + "&" +
    53  		"occupation=" + url.QueryEscape(occupation)
    54  
    55  	path := fmt.Sprintf("https://httpbin.org/get?%s", params)
    56  
    57  	cnt := 0
    58  	for {
    59  		fmt.Printf("Getting %s\r\n\r\n", path)
    60  		resp, err := http.Get(path)
    61  		if err != nil {
    62  			fmt.Printf("%s\r\n", err.Error())
    63  			time.Sleep(10 * time.Second)
    64  			continue
    65  		}
    66  
    67  		fmt.Printf("%s %s\r\n", resp.Proto, resp.Status)
    68  		for k, v := range resp.Header {
    69  			fmt.Printf("%s: %s\r\n", k, strings.Join(v, " "))
    70  		}
    71  		fmt.Printf("\r\n")
    72  
    73  		body, err := io.ReadAll(resp.Body)
    74  		println(string(body))
    75  		resp.Body.Close()
    76  
    77  		cnt++
    78  		fmt.Printf("-------- %d --------\r\n", cnt)
    79  		time.Sleep(10 * time.Second)
    80  	}
    81  }
    82  
    83  // Wait for user to open serial console
    84  func waitSerial() {
    85  	for !machine.Serial.DTR() {
    86  		time.Sleep(100 * time.Millisecond)
    87  	}
    88  }