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

     1  // This example uses TLS to send an HTTPS request to retrieve a webpage
     2  //
     3  // You shall see "strict-transport-security" header in the response,
     4  // this confirms communication is indeed over HTTPS
     5  //
     6  // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
     7  
     8  //go:build ninafw || wioterminal
     9  
    10  package main
    11  
    12  import (
    13  	"bufio"
    14  	"crypto/tls"
    15  	"fmt"
    16  	"io"
    17  	"log"
    18  	"machine"
    19  	"net"
    20  	"strings"
    21  	"time"
    22  
    23  	"tinygo.org/x/drivers/netlink"
    24  	"tinygo.org/x/drivers/netlink/probe"
    25  )
    26  
    27  var (
    28  	ssid string
    29  	pass string
    30  	// HTTPS server address to hit with a GET / request
    31  	address string = "httpbin.org:443"
    32  )
    33  
    34  var conn net.Conn
    35  
    36  // Wait for user to open serial console
    37  func waitSerial() {
    38  	for !machine.Serial.DTR() {
    39  		time.Sleep(100 * time.Millisecond)
    40  	}
    41  }
    42  
    43  func check(err error) {
    44  	if err != nil {
    45  		println("Hit an error:", err.Error())
    46  		panic("BYE")
    47  	}
    48  }
    49  
    50  func readResponse() {
    51  	r := bufio.NewReader(conn)
    52  	resp, err := io.ReadAll(r)
    53  	check(err)
    54  	println(string(resp))
    55  }
    56  
    57  func closeConnection() {
    58  	conn.Close()
    59  }
    60  
    61  func dialConnection() {
    62  	var err error
    63  
    64  	println("\r\n---------------\r\nDialing TLS connection")
    65  	conn, err = tls.Dial("tcp", address, nil)
    66  	for ; err != nil; conn, err = tls.Dial("tcp", address, nil) {
    67  		println("Connection failed:", err.Error())
    68  		time.Sleep(5 * time.Second)
    69  	}
    70  	println("Connected!\r")
    71  }
    72  
    73  func makeRequest() {
    74  	print("Sending HTTPS request...")
    75  	w := bufio.NewWriter(conn)
    76  	fmt.Fprintln(w, "GET /get HTTP/1.1")
    77  	fmt.Fprintln(w, "Host:", strings.Split(address, ":")[0])
    78  	fmt.Fprintln(w, "User-Agent: TinyGo")
    79  	fmt.Fprintln(w, "Connection: close")
    80  	fmt.Fprintln(w)
    81  	check(w.Flush())
    82  	println("Sent!\r\n\r")
    83  }
    84  
    85  func main() {
    86  	waitSerial()
    87  
    88  	link, _ := probe.Probe()
    89  
    90  	err := link.NetConnect(&netlink.ConnectParams{
    91  		Ssid:       ssid,
    92  		Passphrase: pass,
    93  	})
    94  	if err != nil {
    95  		log.Fatal(err)
    96  	}
    97  
    98  	for i := 0; ; i++ {
    99  		dialConnection()
   100  		makeRequest()
   101  		readResponse()
   102  		closeConnection()
   103  		println("--------", i, "--------\r\n")
   104  		time.Sleep(10 * time.Second)
   105  	}
   106  }