1 package httpmock 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 ) 7 8 // File is a file name. The contents of this file is loaded on demand 9 // by the following methods. 10 // 11 // Note that: 12 // file := httpmock.File("file.txt") 13 // fmt.Printf("file: %s\n", file) 14 // 15 // prints the content of file "file.txt" as String() method is used. 16 // 17 // To print the file name, and not its content, simply do: 18 // file := httpmock.File("file.txt") 19 // fmt.Printf("file: %s\n", string(file)) 20 type File string 21 22 // MarshalJSON implements json.Marshaler. 23 // 24 // Useful to be used in conjunction with NewJsonResponse() or 25 // NewJsonResponder() as in: 26 // httpmock.NewJsonResponder(200, httpmock.File("body.json")) 27 func (f File) MarshalJSON() ([]byte, error) { 28 return f.bytes() 29 } 30 31 func (f File) bytes() ([]byte, error) { 32 return ioutil.ReadFile(string(f)) 33 } 34 35 // Bytes returns the content of file as a []byte. If an error occurs 36 // during the opening or reading of the file, it panics. 37 // 38 // Useful to be used in conjunction with NewBytesResponse() or 39 // NewBytesResponder() as in: 40 // httpmock.NewBytesResponder(200, httpmock.File("body.raw").Bytes()) 41 func (f File) Bytes() []byte { 42 b, err := f.bytes() 43 if err != nil { 44 panic(fmt.Sprintf("Cannot read %s: %s", string(f), err)) 45 } 46 return b 47 } 48 49 // String returns the content of file as a string. If an error occurs 50 // during the opening or reading of the file, it panics. 51 // 52 // Useful to be used in conjunction with NewStringResponse() or 53 // NewStringResponder() as in: 54 // httpmock.NewStringResponder(200, httpmock.File("body.txt").String()) 55 func (f File) String() string { 56 return string(f.Bytes()) 57 } 58