| 453 | } |
| 454 | |
| 455 | func ApiGet(ctx context.Context, path string) ([]byte, error) { |
| 456 | if os.Getenv("HISHTORY_SIMULATE_NETWORK_ERROR") != "" { |
| 457 | return nil, fmt.Errorf("simulated network error: dial tcp: lookup api.hishtory.dev") |
| 458 | } |
| 459 | start := time.Now() |
| 460 | req, err := http.NewRequest("GET", GetServerHostname()+path, nil) |
| 461 | if err != nil { |
| 462 | return nil, fmt.Errorf("failed to create GET: %w", err) |
| 463 | } |
| 464 | req.Header.Set("X-Hishtory-Version", "v0."+Version) |
| 465 | req.Header.Set("X-Hishtory-Device-Id", hctx.GetConf(ctx).DeviceId) |
| 466 | req.Header.Set("X-Hishtory-User-Id", data.UserId(hctx.GetConf(ctx).UserSecret)) |
| 467 | resp, err := GetHttpClient().Do(req) |
| 468 | if err != nil { |
| 469 | return nil, fmt.Errorf("failed to GET %s%s: %w", GetServerHostname(), path, err) |
| 470 | } |
| 471 | defer resp.Body.Close() |
| 472 | if resp.StatusCode != 200 { |
| 473 | return nil, fmt.Errorf("failed to GET %s%s: status_code=%d", GetServerHostname(), path, resp.StatusCode) |
| 474 | } |
| 475 | respBody, err := io.ReadAll(resp.Body) |
| 476 | if err != nil { |
| 477 | return nil, fmt.Errorf("failed to read response body from GET %s%s: %w", GetServerHostname(), path, err) |
| 478 | } |
| 479 | duration := time.Since(start) |
| 480 | hctx.GetLogger().Infof("ApiGet(%#v): %d bytes - %s\n", GetServerHostname()+path, len(respBody), duration.String()) |
| 481 | return respBody, nil |
| 482 | } |
| 483 | |
| 484 | func ApiPost(ctx context.Context, path, contentType string, reqBody []byte) ([]byte, error) { |
| 485 | if os.Getenv("HISHTORY_SIMULATE_NETWORK_ERROR") != "" { |