Created
August 7, 2023 03:55
-
-
Save selfboot/a88f2c4cc8f7bd5ef99097be34b988f6 to your computer and use it in GitHub Desktop.
A simple go client that simulates an HTTP request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"context" | |
"github.com/golang/protobuf/proto" | |
myproto "github.com/selfboot/demo/proto" // This assumes that the generated protobuf code is in this package | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
func main() { | |
imageBytes, | |
err: = ioutil.ReadFile("/home/go_proj/83.jpeg") // with your picture path径 | |
if err != nil { | |
log.Fatalf("failed to read file: %v", err) | |
} | |
imageData: = & myproto.OcrCommReq { | |
ImgData: imageBytes, | |
} | |
serializedImageData, err: = proto.Marshal(imageData) | |
if err != nil { | |
log.Fatalf("failed to serialize image data: %v", err) | |
} | |
serializedImageDataTwice, err: = proto.Marshal( & myproto.MeshCallObj { | |
Request: serializedImageData, | |
}) | |
if err != nil { | |
log.Fatalf("failed to serialize image data twice: %v", err) | |
} | |
req, err: = http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8089", bytes.NewBuffer(serializedImageDataTwice)) | |
if err != nil { | |
log.Fatalf("failed to create request: %v", err) | |
} | |
req.Header.Set("Content-Type", "application/x-protobuf") | |
client: = & http.Client {} | |
resp, err: = client.Do(req) | |
if err != nil { | |
log.Fatalf("failed to send request: %v", err) | |
} | |
defer resp.Body.Close() | |
log.Printf("response header: %v", resp.Header) | |
log.Printf("Transfer-Encoding: %v", resp.Header.Get("Transfer-Encoding")) | |
body, err: = ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatalf("failed to read response: %v", err) | |
} | |
if len(body) > 100 { | |
log.Printf("first 100 bytes of response body: %v", string(body[: 100])) | |
} else { | |
log.Printf("response body: %v", string(body)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment