File: file.go

package info (click to toggle)
golang-github-jarcoal-httpmock 1.0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 220 kB
  • sloc: makefile: 2
file content (57 lines) | stat: -rw-r--r-- 1,618 bytes parent folder | download
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
package httpmock

import (
	"fmt"
	"io/ioutil"
)

// 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 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 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 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())
}