How to use ContentType method of tdhttp Package

Best Go-testdeep code snippet using tdhttp.ContentType

request.go

Source:request.go Github

copy

Full Screen

...131}132func postMultipartFormData(target string, data *MultipartBody, headersQueryParams ...any) (*http.Request, error) {133 return newRequest(134 http.MethodPost, target, data,135 append(headersQueryParams, "Content-Type", data.ContentType()),136 )137}138func put(target string, body io.Reader, headersQueryParams ...any) (*http.Request, error) {139 return newRequest(http.MethodPut, target, body, headersQueryParams)140}141func patch(target string, body io.Reader, headersQueryParams ...any) (*http.Request, error) {142 return newRequest(http.MethodPatch, target, body, headersQueryParams)143}144func del(target string, body io.Reader, headersQueryParams ...any) (*http.Request, error) {145 return newRequest(http.MethodDelete, target, body, headersQueryParams)146}147// NewRequest creates a new HTTP request as [httptest.NewRequest]148// does, with the ability to immediately add some headers and/or some149// query parameters....

Full Screen

Full Screen

example_test.go

Source:example_test.go Github

copy

Full Screen

1// Copyright (c) 2020, Maxime Soulé2// All rights reserved.3//4// This source code is licensed under the BSD-style license found in the5// LICENSE file in the root directory of this source tree.6package tdhttp_test7import (8 "encoding/json"9 "encoding/xml"10 "fmt"11 "io"12 "net/http"13 "net/url"14 "strconv"15 "strings"16 "sync"17 "testing"18 "time"19 "github.com/maxatome/go-testdeep/helpers/tdhttp"20 "github.com/maxatome/go-testdeep/td"21)22func Example() {23 t := &testing.T{}24 // Our API handle Persons with 3 routes:25 // - POST /person26 // - GET /person/{personID}27 // - DELETE /person/{personID}28 // Person describes a person.29 type Person struct {30 ID int64 `json:"id,omitempty" xml:"ID,omitempty"`31 Name string `json:"name" xml:"Name"`32 Age int `json:"age" xml:"Age"`33 CreatedAt *time.Time `json:"created_at,omitempty" xml:"CreatedAt,omitempty"`34 }35 // Error is returned to the client in case of error.36 type Error struct {37 Mesg string `json:"message" xml:"Message"`38 Code int `json:"code" xml:"Code"`39 }40 // Our µDB :)41 var mu sync.Mutex42 personByID := map[int64]*Person{}43 personByName := map[string]*Person{}44 var lastID int6445 // reply is a helper to send responses.46 reply := func(w http.ResponseWriter, status int, contentType string, body any) {47 if body == nil {48 w.WriteHeader(status)49 return50 }51 w.Header().Set("Content-Type", contentType)52 w.WriteHeader(status)53 switch contentType {54 case "application/json":55 json.NewEncoder(w).Encode(body) //nolint: errcheck56 case "application/xml":57 xml.NewEncoder(w).Encode(body) //nolint: errcheck58 default: // text/plain59 fmt.Fprintf(w, "%+v", body)60 }61 }62 // Our API63 mux := http.NewServeMux()64 // POST /person65 mux.HandleFunc("/person", func(w http.ResponseWriter, req *http.Request) {66 if req.Method != http.MethodPost {67 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)68 return69 }70 if req.Body == nil {71 http.Error(w, "Bad request", http.StatusBadRequest)72 return73 }74 defer req.Body.Close()75 var in Person76 var contentType string77 switch req.Header.Get("Content-Type") {78 case "application/json":79 err := json.NewDecoder(req.Body).Decode(&in)80 if err != nil {81 http.Error(w, "Bad request", http.StatusBadRequest)82 return83 }84 case "application/xml":85 err := xml.NewDecoder(req.Body).Decode(&in)86 if err != nil {87 http.Error(w, "Bad request", http.StatusBadRequest)88 return89 }90 case "application/x-www-form-urlencoded":91 b, err := io.ReadAll(req.Body)92 if err != nil {93 http.Error(w, "Bad request", http.StatusBadRequest)94 return95 }96 v, err := url.ParseQuery(string(b))97 if err != nil {98 http.Error(w, "Bad request", http.StatusBadRequest)99 return100 }101 in.Name = v.Get("name")102 in.Age, err = strconv.Atoi(v.Get("age"))103 if err != nil {104 http.Error(w, "Bad request", http.StatusBadRequest)105 return106 }107 default:108 http.Error(w, "Unsupported media type", http.StatusUnsupportedMediaType)109 return110 }111 contentType = req.Header.Get("Accept")112 if in.Name == "" || in.Age <= 0 {113 reply(w, http.StatusBadRequest, contentType, Error{114 Mesg: "Empty name or bad age",115 Code: http.StatusBadRequest,116 })117 return118 }119 mu.Lock()120 defer mu.Unlock()121 if personByName[in.Name] != nil {122 reply(w, http.StatusConflict, contentType, Error{123 Mesg: "Person already exists",124 Code: http.StatusConflict,125 })126 return127 }128 lastID++129 in.ID = lastID130 now := time.Now()131 in.CreatedAt = &now132 personByID[in.ID] = &in133 personByName[in.Name] = &in134 reply(w, http.StatusCreated, contentType, in)135 })136 // GET /person/{id}137 // DELETE /person/{id}138 mux.HandleFunc("/person/", func(w http.ResponseWriter, req *http.Request) {139 id, err := strconv.ParseInt(strings.TrimPrefix(req.URL.Path, "/person/"), 10, 64)140 if err != nil {141 http.Error(w, "Bad request", http.StatusBadRequest)142 return143 }144 accept := req.Header.Get("Accept")145 mu.Lock()146 defer mu.Unlock()147 if personByID[id] == nil {148 reply(w, http.StatusNotFound, accept, Error{149 Mesg: "Person does not exist",150 Code: http.StatusNotFound,151 })152 return153 }154 switch req.Method {155 case http.MethodGet:156 reply(w, http.StatusOK, accept, personByID[id])157 case http.MethodDelete:158 delete(personByID, id)159 reply(w, http.StatusNoContent, "", nil)160 default:161 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)162 }163 })164 //165 // Let's test our API166 //167 ta := tdhttp.NewTestAPI(t, mux)168 // Re-usable custom operator to check Content-Type header169 contentTypeIs := func(ct string) td.TestDeep {170 return td.SuperMapOf(http.Header{"Content-Type": []string{ct}}, nil)171 }172 //173 // Person not found174 //175 ta.Get("/person/42", "Accept", "application/json").176 Name("GET /person/42 - JSON").177 CmpStatus(404).178 CmpHeader(contentTypeIs("application/json")).179 CmpJSONBody(Error{180 Mesg: "Person does not exist",181 Code: 404,182 })183 fmt.Println("GET /person/42 - JSON:", !ta.Failed())184 ta.Get("/person/42", "Accept", "application/xml").185 Name("GET /person/42 - XML").186 CmpStatus(404).187 CmpHeader(contentTypeIs("application/xml")).188 CmpXMLBody(Error{189 Mesg: "Person does not exist",190 Code: 404,191 })192 fmt.Println("GET /person/42 - XML:", !ta.Failed())193 ta.Get("/person/42", "Accept", "text/plain").194 Name("GET /person/42 - raw").195 CmpStatus(404).196 CmpHeader(contentTypeIs("text/plain")).197 CmpBody("{Mesg:Person does not exist Code:404}")198 fmt.Println("GET /person/42 - raw:", !ta.Failed())199 //200 // Create a Person201 //202 var bobID int64203 ta.PostXML("/person", Person{Name: "Bob", Age: 32},204 "Accept", "application/xml").205 Name("POST /person - XML").206 CmpStatus(201).207 CmpHeader(contentTypeIs("application/xml")).208 CmpXMLBody(Person{ // using operator anchoring directly in literal209 ID: ta.A(td.Catch(&bobID, td.NotZero()), int64(0)).(int64),210 Name: "Bob",211 Age: 32,212 CreatedAt: ta.A(td.Ptr(td.Between(ta.SentAt(), time.Now()))).(*time.Time),213 })214 fmt.Printf("POST /person - XML: %t → Bob ID=%d\n", !ta.Failed(), bobID)215 var aliceID int64216 ta.PostJSON("/person", Person{Name: "Alice", Age: 35},217 "Accept", "application/json").218 Name("POST /person - JSON").219 CmpStatus(201).220 CmpHeader(contentTypeIs("application/json")).221 CmpJSONBody(td.JSON(` // using JSON operator (yes comment allowed in JSON!)222{223 "id": $1,224 "name": "Alice",225 "age": 35,226 "created_at": $2227}`,228 td.Catch(&aliceID, td.NotZero()),229 td.Smuggle(func(date string) (time.Time, error) {230 return time.Parse(time.RFC3339Nano, date)231 }, td.Between(ta.SentAt(), time.Now()))))232 fmt.Printf("POST /person - JSON: %t → Alice ID=%d\n", !ta.Failed(), aliceID)233 var brittID int64234 ta.PostForm("/person",235 url.Values{236 "name": []string{"Britt"},237 "age": []string{"29"},238 },239 "Accept", "text/plain").240 Name("POST /person - raw").241 CmpStatus(201).242 CmpHeader(contentTypeIs("text/plain")).243 // using Re (= Regexp) operator244 CmpBody(td.Re(`\{ID:(\d+) Name:Britt Age:29 CreatedAt:.*\}\z`,245 td.Smuggle(func(groups []string) (int64, error) {246 return strconv.ParseInt(groups[0], 10, 64)247 }, td.Catch(&brittID, td.NotZero()))))248 fmt.Printf("POST /person - raw: %t → Britt ID=%d\n", !ta.Failed(), brittID)249 //250 // Get a Person251 //252 ta.Get(fmt.Sprintf("/person/%d", aliceID), "Accept", "application/xml").253 Name("GET Alice - XML (ID #%d)", aliceID).254 CmpStatus(200).255 CmpHeader(contentTypeIs("application/xml")).256 CmpXMLBody(td.SStruct( // using SStruct operator257 Person{258 ID: aliceID,259 Name: "Alice",260 Age: 35,261 },262 td.StructFields{263 "CreatedAt": td.Ptr(td.NotZero()),264 },265 ))266 fmt.Println("GET XML Alice:", !ta.Failed())267 ta.Get(fmt.Sprintf("/person/%d", aliceID), "Accept", "application/json").268 Name("GET Alice - JSON (ID #%d)", aliceID).269 CmpStatus(200).270 CmpHeader(contentTypeIs("application/json")).271 CmpJSONBody(td.JSON(` // using JSON operator (yes comment allowed in JSON!)272{273 "id": $1,274 "name": "Alice",275 "age": 35,276 "created_at": $2277}`,278 aliceID,279 td.Not(td.Re(`^0001-01-01`)), // time is not 0001-01-01… aka zero time.Time280 ))281 fmt.Println("GET JSON Alice:", !ta.Failed())282 //283 // Delete a Person284 //285 ta.Delete(fmt.Sprintf("/person/%d", aliceID), nil).286 Name("DELETE Alice (ID #%d)", aliceID).287 CmpStatus(204).288 CmpHeader(td.Not(td.ContainsKey("Content-Type"))).289 NoBody()290 fmt.Println("DELETE Alice:", !ta.Failed())291 // Check Alice is deleted292 ta.Get(fmt.Sprintf("/person/%d", aliceID), "Accept", "application/json").293 Name("GET (deleted) Alice - JSON (ID #%d)", aliceID).294 CmpStatus(404).295 CmpHeader(contentTypeIs("application/json")).296 CmpJSONBody(td.JSON(`297{298 "message": "Person does not exist",299 "code": 404300}`))301 fmt.Println("Alice is not found anymore:", !ta.Failed())302 // Output:303 // GET /person/42 - JSON: true304 // GET /person/42 - XML: true305 // GET /person/42 - raw: true306 // POST /person - XML: true → Bob ID=1307 // POST /person - JSON: true → Alice ID=2308 // POST /person - raw: true → Britt ID=3309 // GET XML Alice: true310 // GET JSON Alice: true311 // DELETE Alice: true312 // Alice is not found anymore: true313}...

Full Screen

Full Screen

multipart_test.go

Source:multipart_test.go Github

copy

Full Screen

...263 _, err = rd.NextPart()264 assert.Cmp(err, io.EOF)265 }266 multi := tdhttp.MultipartBody{}267 td.Cmp(t, multi.ContentType(), `multipart/form-data; boundary="go-testdeep-42"`)268 td.Cmp(t, multi.Boundary, "go-testdeep-42",269 "Boundary field set with default value")270 td.CmpEmpty(t, multi.MediaType, "MediaType field NOT set")271 multi.Boundary = "BoUnDaRy"272 td.Cmp(t, multi.ContentType(), `multipart/form-data; boundary="BoUnDaRy"`)273 multi.MediaType = "multipart/mixed"274 td.Cmp(t, multi.ContentType(), `multipart/mixed; boundary="BoUnDaRy"`)275}...

Full Screen

Full Screen

ContentType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := minify.New()4 m.AddFunc("text/html", html.Minify)5 m.AddFunc("text/css", css.Minify)6 m.AddFunc("text/javascript", js.Minify)7 m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)8 m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)9 m.Add("text/html", &html.Minifier{10 })11 m.Add("text/css", &css.Minifier{12 })13 m.Add("text/javascript", &js.Minifier{14 })15 m.AddRegexp(regexp.MustCompile("[/+]json$"), &json.Minifier{16 })17 m.AddRegexp(regexp.MustCompile("[/+]xml$"), &xml.Minifier{18 })19 m.Minify("text/html", os.Stdout, os.Stdin)20 m.Minify("text/css", os.Stdout, os.Stdin)

Full Screen

Full Screen

ContentType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3m := minify.New()4m.AddFunc("text/html", html.Minify)5m.AddFunc("text/css", css.Minify)6m.AddFunc("text/javascript", js.Minify)7m.AddFunc("image/svg+xml", svg.Minify)8m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)9m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)10h := tdhttp.Minify(m)11}12import (13func main() {14 m := minify.New()15 m.AddFunc("text/html", html.Minify)16 m.AddFunc("text/css", css.Minify)17 m.AddFunc("text/javascript", js.Minify)18 m.AddFunc("image/svg+xml", svg.Minify)19 m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)20 m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)21 h := tdhttp.Minify(m)22}

Full Screen

Full Screen

ContentType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3m := minify.New()4m.AddFunc("text/css", css.Minify)5m.AddFunc("text/html", html.Minify)6m.AddFunc("text/javascript", js.Minify)7m.AddFunc("application/json", json.Minify)8m.AddFunc("image/svg+xml", svg.Minify)9m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)10fmt.Println(m.String("text/html", `11}

Full Screen

Full Screen

ContentType

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "github.com/tdewolff/parse/v2"3import "github.com/tdewolff/parse/v2/html"4import "github.com/tdewolff/parse/v2/tdhttp"5func main() {6 r := parse.NewInputString(str)7 tokenizer := html.NewTokenizer(r)8 for {9 tokenizer.Next()10 if tokenizer.TokenType == html.ErrorToken {11 }12 if tokenizer.TokenType == html.StartTagToken {13 if tdhttp.ContentType(tokenizer.Token) == tdhttp.TextHTML {14 fmt.Println("ContentType is TextHTML")15 }16 }17 }18}19import "fmt"20import "github.com/tdewolff/parse/v2"21import "github.com/tdewolff/parse/v2/html"22import "github.com/tdewolff/parse/v2/tdhttp"23func main() {24 r := parse.NewInputString(str)25 tokenizer := html.NewTokenizer(r)26 for {27 tokenizer.Next()28 if tokenizer.TokenType == html.ErrorToken {29 }30 if tokenizer.TokenType == html.StartTagToken {31 if tdhttp.ContentLength(tokenizer.Token) == 24 {32 fmt.Println("ContentLength is 24")33 }34 }35 }36}37import "fmt"38import "github.com/tdewolff/parse/v2"39import "github.com/tdewolff/parse/v2/html"40import "github.com/tdewolff/parse/v2/tdhttp"41func main() {42 r := parse.NewInputString(str)43 tokenizer := html.NewTokenizer(r)44 for {45 tokenizer.Next()46 if tokenizer.TokenType == html.ErrorToken {47 }

Full Screen

Full Screen

ContentType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{}4 if err != nil {5 fmt.Println("Error creating the request", err)6 }7 req.Header.Add("Accept", "text/html")8 resp, err := client.Do(req)9 if err != nil {10 fmt.Println("Error sending the request", err)11 }12 fmt.Println(resp.Header.Get("Content-Type"))13}14text/html; charset=ISO-8859-115func (c *Client) SetCookie(req *Request, cookie *Cookie)16import (17func main() {18 client := &http.Client{}19 if err != nil {20 fmt.Println("Error creating the request", err)21 }22 cookie := &http.Cookie{23 }24 client.SetCookie(req, cookie)25 resp, err := client.Do(req)26 if err != nil {27 fmt.Println("Error sending the request", err)28 }29 fmt.Println("Status", resp.Status)30}

Full Screen

Full Screen

ContentType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 contentType := tdhttp.ContentType(url)4 fmt.Println(contentType)5}6text/html; charset=utf-8

Full Screen

Full Screen

ContentType

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(tdhttp.ContentType("image.jpg"))4 fmt.Println(tdhttp.ContentType("file.txt"))5}6import (7func main() {8 fmt.Println(tdhttp.ContentType("image.jpg"))9 fmt.Println(tdhttp.ContentType("file.txt"))10}11import (12func main() {13 fmt.Println(tdhttp.ContentType("image.jpg"))14 fmt.Println(tdhttp.ContentType("file.txt"))15}16import (17func main() {18 fmt.Println(tdhttp.ContentType("image.jpg"))19 fmt.Println(tdhttp.ContentType("file.txt"))20}21import (22func main() {23 fmt.Println(tdhttp.ContentType("image.jpg"))24 fmt.Println(tdhttp.ContentType("file.txt"))25}

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