meetup-golang-2024-demo/curl.go

36 lines
684 B
Go
Raw Permalink Normal View History

2024-05-29 10:09:31 +00:00
package main
import (
2024-05-29 14:00:19 +00:00
"bytes"
2024-05-29 10:09:31 +00:00
"fmt"
"io"
"net"
"net/http"
)
2024-05-29 14:00:19 +00:00
func curl(socket, method, path string, body []byte) (io.ReadCloser, error) {
2024-05-29 10:09:31 +00:00
socketDial := func(proto, addr string) (conn net.Conn, err error) {
return net.Dial("unix", socket)
}
tr := &http.Transport{
Dial: socketDial,
}
client := &http.Client{
Transport: tr,
}
2024-05-29 14:00:19 +00:00
req, err := http.NewRequest(method, path, bytes.NewReader(body))
2024-05-29 10:09:31 +00:00
if err != nil {
return nil, fmt.Errorf("Error creating request: %w\n", err)
}
2024-05-29 14:00:19 +00:00
req.Header.Add("Content-Type", "application/json")
2024-05-29 10:09:31 +00:00
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error performing request: %w\n", err)
}
return resp.Body, nil
}