package fairwind import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "strings" ) type HTTPClientRequest struct { Data string Object any Encoding int } type HTTPCLientResponse struct { Raw []byte Object any Encoding int } type HTTPClient struct { scheme string host string port string } func NewHTTPClient(scheme string, host string, port string) *HTTPClient { return &HTTPClient{ scheme: scheme, host: host, port: port, } } func (this *HTTPClient) Request(method int, path string, headers HTTPHeaders, request *HTTPClientRequest, response *HTTPCLientResponse) error { buffer, err := json.Marshal(request.Object) if err != nil { return err } var requestInternal *http.Request if method == METHOD_GET { requestInternal, err = http.NewRequest( "GET", fmt.Sprintf("%s://%s:%s%s", this.scheme, this.host, this.port, path), nil, ) } if method == METHOD_POST { requestInternal, err = http.NewRequest( "POST", fmt.Sprintf("%s://%s:%s%s", this.scheme, this.host, this.port, path), bytes.NewBuffer(buffer), ) } if err != nil { return err } for key, value := range headers { requestInternal.Header.Add(key, value) } client := &http.Client{} responseInternal, err := client.Do(requestInternal) if err != nil { return err } if responseInternal.StatusCode != http.StatusOK { return fmt.Errorf("invalid status = %d", responseInternal.StatusCode) } buffer, err = io.ReadAll(responseInternal.Body) if err != nil { return err } contentTypeHeader := responseInternal.Header.Get("Content-Type") if contentTypeHeader == "" { return errors.New("content-type not specified") } var contentType string if contentTypeHeader == "text/plain" || contentTypeHeader == "application/json" || contentTypeHeader == "application/octet-stream" { contentType = contentTypeHeader } else { parts := strings.Split(contentTypeHeader, ";") if len(parts) != 2 { return errors.New("content-type invalid") } contentType = parts[0] } switch contentType { case "text/plain": case "application/octet-stream": response.Raw = buffer case "application/json": err = json.Unmarshal(buffer, response.Object) if err != nil { return err } } return nil }