// Package gostate demonstrates an exact state round trip without decoding // customer JSON into floating-point values. It performs no automatic retries. package gostate import ( "bytes" "context" _ "embed" "errors" "io" "net/http" "net/url" "strings" "time" ) //go:embed state.go var Source string // RoundTrip uses a caller-owned TLS client and authorized project credential. // Production callers should use a transport without an ambient proxy and keep // credentials in protected memory. A failed write may already have committed. func RoundTrip(ctx context.Context, client *http.Client, origin, project, credential string) ([]byte, error) { parsed, err := url.Parse(origin) if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil || parsed.Path != "" || parsed.RawQuery != "" || parsed.Fragment != "" || client == nil || project == "" || strings.ContainsAny(project, "/\\\r\n") || credential == "" || strings.ContainsAny(credential, "\r\n") { return nil, errors.New("invalid example configuration") } bounded := *client bounded.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } bounded.Timeout = 30 * time.Second ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() path := origin + "/api/v1/projects/" + url.PathEscape(project) + "/state/examples/go-checkpoint" value := []byte(`{"value":{"exact":9007199254740993}}`) for _, method := range []string{http.MethodPut, http.MethodGet} { var body io.Reader if method == http.MethodPut { body = bytes.NewReader(value) } request, err := http.NewRequestWithContext(ctx, method, path, body) if err != nil { return nil, errors.New("invalid example request") } request.Header.Set("Authorization", "Bearer "+credential) if method == http.MethodPut { request.Header.Set("Content-Type", "application/json") request.Header.Set("If-None-Match", "*") } response, err := bounded.Do(request) if err != nil { return nil, errors.New("transport failed; reconcile before retrying") } raw, readErr := io.ReadAll(io.LimitReader(response.Body, 131073)) response.Body.Close() if readErr != nil || len(raw) > 131072 || response.StatusCode != 200 { return nil, errors.New("state request failed; inspect authorized status before retrying") } if method == http.MethodGet { return raw, nil } } return nil, errors.New("state read missing") }