// Send one GET with Go net/http defaults and print one JSON line.
//
// Usage: go_client URL
// http.DefaultTransport uses http.ProxyFromEnvironment, which applies the
// golang.org/x/net/http/httpproxy rules vendored in the standard library.
// The route decision is observed by the lab proxy, not reported here.
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"runtime"
	"strings"
	"time"
)

type result struct {
	OK     bool    `json:"ok"`
	Status *int    `json:"status"`
	Marker *string `json:"marker"`
	Error  *string `json:"error"`
}

func emit(v any, code int) {
	b, _ := json.Marshal(v)
	fmt.Println(string(b))
	os.Exit(code)
}

func main() {
	url := os.Args[1]
	if url == "--version" {
		emit(map[string]string{"go": runtime.Version()}, 0)
	}
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		msg := err.Error()
		if len(msg) > 300 {
			msg = msg[:300]
		}
		emit(result{Error: &msg}, 1)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	status := resp.StatusCode
	var m *string
	for _, pair := range [][2]string{{"C08-PROXY", "proxy"}, {"C08-ORIGIN", "origin"}} {
		if strings.Contains(string(body), pair[0]) {
			v := pair[1]
			m = &v
			break
		}
	}
	emit(result{OK: true, Status: &status, Marker: m}, 0)
}
