How to use SubmitForm method of http Package

Best K6 code snippet using http.SubmitForm

algod.go

Source:algod.go Github

copy

Full Screen

1package algod2import (3 "bytes"4 "encoding/json"5 "fmt"6 "io"7 "io/ioutil"8 "net/http"9 "net/url"10 "strings"11 "github.com/google/go-querystring/query"12)13const (14 authHeader = "X-Algo-API-Token"15 healthCheckEndpoint = "/health"16 apiVersionPathPrefix = "/v1"17)18// unversionedPaths ais a set of paths that should not be prefixed by the API version19var unversionedPaths = map[string]bool{20 "/versions": true,21 "/health": true,22}23// rawRequestPaths is a set of paths where the body should not be urlencoded24var rawRequestPaths = map[string]bool{25 "/transactions": true,26}27// Client manages the REST interface for a calling user.28type Client struct {29 serverURL url.URL30 apiToken string31}32// MakeClient is the factory for constructing a Client for a given endpoint33func MakeClient(address string, apiToken string) (c Client, err error) {34 url, err := url.Parse(address)35 if err != nil {36 return37 }38 c = Client{39 serverURL: *url,40 apiToken: apiToken,41 }42 return43}44// extractError checks if the response signifies an error (for now, StatusCode != 200).45// If so, it returns the error.46// Otherwise, it returns nil.47func extractError(resp *http.Response) error {48 if resp.StatusCode == 200 {49 return nil50 }51 errorBuf, _ := ioutil.ReadAll(resp.Body) // ignore returned error52 return fmt.Errorf("HTTP %v: %s", resp.Status, errorBuf)53}54// stripTransaction gets a transaction of the form "tx-XXXXXXXX" and truncates the "tx-" part, if it starts with "tx-"55func stripTransaction(tx string) string {56 if strings.HasPrefix(tx, "tx-") {57 return strings.SplitAfter(tx, "-")[1]58 }59 return tx60}61// submitForm is a helper used for submitting (ex.) GETs and POSTs to the server62func (client Client) submitForm(response interface{}, path string, request interface{}, requestMethod string, encodeJSON bool) error {63 var err error64 queryURL := client.serverURL65 queryURL.Path = path66 // Handle version prefix67 if !unversionedPaths[path] {68 queryURL.Path = strings.Join([]string{apiVersionPathPrefix, path}, "")69 }70 var req *http.Request71 var body io.Reader72 if request != nil {73 if rawRequestPaths[path] {74 reqBytes, ok := request.([]byte)75 if !ok {76 return fmt.Errorf("couldn't decode raw request as bytes")77 }78 body = bytes.NewBuffer(reqBytes)79 } else {80 v, err := query.Values(request)81 if err != nil {82 return err83 }84 queryURL.RawQuery = v.Encode()85 if encodeJSON {86 jsonValue, _ := json.Marshal(request)87 body = bytes.NewBuffer(jsonValue)88 }89 }90 }91 req, err = http.NewRequest(requestMethod, queryURL.String(), body)92 if err != nil {93 return err94 }95 // If we add another endpoint that does not require auth, we should add a96 // requiresAuth argument to submitForm rather than checking here97 if path != healthCheckEndpoint {98 req.Header.Set(authHeader, client.apiToken)99 }100 httpClient := &http.Client{}101 resp, err := httpClient.Do(req)102 if err != nil {103 return err104 }105 defer resp.Body.Close()106 err = extractError(resp)107 if err != nil {108 return err109 }110 dec := json.NewDecoder(resp.Body)111 return dec.Decode(&response)112}113// get performs a GET request to the specific path against the server114func (client Client) get(response interface{}, path string, request interface{}) error {115 return client.submitForm(response, path, request, "GET", false /* encodeJSON */)116}117// post sends a POST request to the given path with the given request object.118// No query parameters will be sent if request is nil.119// response must be a pointer to an object as post writes the response there.120func (client Client) post(response interface{}, path string, request interface{}) error {121 return client.submitForm(response, path, request, "POST", true /* encodeJSON */)122}123// as post, but with MethodPut124func (client Client) put(response interface{}, path string, request interface{}) error {125 return client.submitForm(response, path, request, "PUT", true /* encodeJSON */)126}127// as post, but with MethodPatch128func (client Client) patch(response interface{}, path string, request interface{}) error {129 return client.submitForm(response, path, request, "PATCH", true /* encodeJSON */)130}...

Full Screen

Full Screen

server.go

Source:server.go Github

copy

Full Screen

1package main2import (3 "fmt"4 "io/ioutil"5 "log"6 "net/http"7)8func sayhelloName(w http.ResponseWriter, r *http.Request) {9 a := `<!DOCTYPE html>10<html>11<head>12 <meta charset="UTF-8">13 <title>CORS跨域</title>14 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>15</head>16<body>17<script type="text/javascript">18 function sub(submitform) {19 var formData= new FormData(document.getElementById(submitform));20 $.ajax({21 url: "test",22 type: 'POST',23 data: formData,24 dataType: "json", //返回数据形式为json25 contentType: false,26 cache: false,27 processData: false,28 success: function (msg) {29 if (msg == 'success') {30 alert("成功")31 }32 33 },34 error: function (msg) {35 alert(msg)36 }37 });38 }39 </script>40 41<form action="" method="post" id="submitform" enctype="multipart/form-data">42 <input type="text" name="fileName" id="fileName"/><p></p>43 <input type="file" name="fileUrl"/>44 <input type="button" onclick="sub('submitform')"/>45</form>46</body>47</html>`48 _, err := w.Write([]byte(a))49 if err != nil {50 fmt.Println(err)51 return52 }53}54func formTest(w http.ResponseWriter, r *http.Request) {55 bodyBytes, err := ioutil.ReadAll(r.Body)56 if err != nil {57 fmt.Println(err)58 return59 }60 fmt.Println(string(bodyBytes))61}62func main() {63 http.HandleFunc("/", sayhelloName) //设置访问的路由64 http.HandleFunc("/test", formTest) //设置访问的路由65 err := http.ListenAndServe(":9090", nil) //设置监听的端口66 if err != nil {67 log.Fatal("ListenAndServe: ", err)68 }69}...

Full Screen

Full Screen

SubmitForm

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 panic(err)5 }6 defer resp.Body.Close()7 fmt.Println("Response status:", resp.Status)8}9import (10func main() {11 if err != nil {12 panic(err)13 }14 defer resp.Body.Close()15 fmt.Println("Response status:", resp.Status)16}17import (18func main() {19 if err != nil {20 panic(err)21 }22 defer resp.Body.Close()23 fmt.Println("Response status:", resp.Status)24}25import (26func main() {27 if err != nil {28 panic(err)29 }30 defer resp.Body.Close()31 fmt.Println("Response status:", resp.Status)32}33import (34func main() {35 if err != nil {36 panic(err)37 }38 defer resp.Body.Close()39 fmt.Println("Response status:", resp.Status)40}41import (42func main() {43 if err != nil {44 panic(err)45 }46 defer resp.Body.Close()47 fmt.Println("Response status:", resp.Status)48}

Full Screen

Full Screen

SubmitForm

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 defer resp.Body.Close()7}8import (9func main() {10 if err != nil {11 log.Fatal(err)12 }13 defer resp.Body.Close()14}15import (16func main() {17 if err != nil {18 log.Fatal(err)19 }20 defer resp.Body.Close()21}22import (23func main() {24 if err != nil {25 log.Fatal(err)26 }27 defer resp.Body.Close()28}29import (30func main() {31 if err != nil {32 log.Fatal(err)33 }34 defer resp.Body.Close()35}36import (37func main() {38 if err != nil {

Full Screen

Full Screen

SubmitForm

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data := url.Values{}4 data.Set("q", "golang")5 resp, err := http.PostForm(url, data)6 if err != nil {7 fmt.Println(err)8 }9 defer resp.Body.Close()10 fmt.Println("response Status:", resp.Status)11 fmt.Println("response Headers:", resp.Header)12 body, _ := ioutil.ReadAll(resp.Body)13 fmt.Println("response Body:", string(body))14}15response Headers: map[Alt-Svc:[h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="43,42,41,39,35"] Cache-Control:[private, max-age=0] Content-Encoding:[gzip] Content-Type:[text/html; charset=ISO-8859-1] Date:[Wed, 06 Nov 2019 10:32:14 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] Set-Cookie:[1P_JAR=2019-11-06-10; expi

Full Screen

Full Screen

SubmitForm

Using AI Code Generation

copy

Full Screen

1func main() {2 if err != nil {3 log.Fatal(err)4 }5 defer resp.Body.Close()6 body, err := ioutil.ReadAll(resp.Body)7 if err != nil {8 log.Fatal(err)9 }10 fmt.Println(resp.Status)11 fmt.Println(string(body))12}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful