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

     1  // This example posts an URL using http.Post().  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.Post().
     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  	"bytes"
    18  	"fmt"
    19  	"io"
    20  	"log"
    21  	"machine"
    22  	"net/http"
    23  	"time"
    24  
    25  	"tinygo.org/x/drivers/netlink"
    26  	"tinygo.org/x/drivers/netlink/probe"
    27  )
    28  
    29  var (
    30  	ssid string
    31  	pass string
    32  )
    33  
    34  func main() {
    35  
    36  	waitSerial()
    37  
    38  	link, _ := probe.Probe()
    39  
    40  	err := link.NetConnect(&netlink.ConnectParams{
    41  		Ssid:       ssid,
    42  		Passphrase: pass,
    43  	})
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  
    48  	path := "https://httpbin.org/post"
    49  	data := []byte("{\"name\":\"John Doe\",\"occupation\":\"gardener\"}")
    50  
    51  	resp, err := http.Post(path, "application/json", bytes.NewBuffer(data))
    52  	if err != nil {
    53  		log.Fatal(err)
    54  	}
    55  	defer resp.Body.Close()
    56  
    57  	body, err := io.ReadAll(resp.Body)
    58  	if err != nil {
    59  		log.Fatal(err)
    60  	}
    61  
    62  	fmt.Println(string(body))
    63  
    64  	link.NetDisconnect()
    65  }
    66  
    67  // Wait for user to open serial console
    68  func waitSerial() {
    69  	for !machine.Serial.DTR() {
    70  		time.Sleep(100 * time.Millisecond)
    71  	}
    72  }