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