Debian Codegraph @

lib/examples/compare-chromedp/upload/main.go

raw
1 // Package main ...
2 package main
3
4 import (
5 "fmt"
6 "io"
7 "log"
8 "net"
9 "net/http"
10 "os"
11
12 "github.com/go-rod/rod"
13 )
14
15 // This example demonstrates how to upload a file on a form.
16 func main() {
17 host := uploadServer()
18
19 page := rod.New().MustConnect().MustPage(host)
20
21 page.MustElement(`input[name="upload"]`).MustSetFiles("./main.go")
22 page.MustElement(`input[name="submit"]`).MustClick()
23
24 log.Printf(
25 "original size: %d, upload size: %s",
26 size("./main.go"),
27 page.MustElement("#result").MustText(),
28 )
29 }
30
31 // get some info about the file.
32 func size(file string) int {
33 fi, err := os.Stat(file)
34 if err != nil {
35 panic(err)
36 }
37 return int(fi.Size())
38 }
39
40 func uploadServer() string {
41 // create http server and result channel
42 mux := http.NewServeMux()
43 mux.HandleFunc("/", func(res http.ResponseWriter, _ *http.Request) {
44 _, _ = fmt.Fprint(res, uploadHTML)
45 })
46 mux.HandleFunc("/upload", func(res http.ResponseWriter, req *http.Request) {
47 f, _, err := req.FormFile("upload")
48 if err != nil {
49 http.Error(res, err.Error(), http.StatusBadRequest)
50 return
51 }
52 defer func() { _ = f.Close() }()
53
54 buf, err := io.ReadAll(f)
55 if err != nil {
56 http.Error(res, err.Error(), http.StatusBadRequest)
57 return
58 }
59
60 _, _ = fmt.Fprintf(res, resultHTML, len(buf))
61 })
62 l, _ := net.Listen("tcp4", "127.0.0.1:0")
63 go func() { _ = http.Serve(l, mux) }()
64 return "http://" + l.Addr().String()
65 }
66
67 const (
68 uploadHTML = `<!doctype html>
69 <html>
70 <body>
71 <form method="POST" action="/upload" enctype="multipart/form-data">
72 <input name="upload" type="file"/>
73 <input name="submit" type="submit"/>
74 </form>
75 </body>
76 </html>`
77
78 resultHTML = `<!doctype html>
79 <html>
80 <body>
81 <div id="result">%d</div>
82 </body>
83 </html>`
84 )