Files
7000pctAUTO efb912c3dc
Some checks failed
CI / test (push) Has been cancelled
Fix CI issues: add workflow file and fix lint errors
2026-03-22 10:53:57 +00:00

102 lines
3.2 KiB
Go

{"""Go code generator."""
import json
import re
from curlconverter.parser import ParsedCurl
from curlconverter.generators import register_generator
def _detect_content_type(headers: dict, data: str) -> str:
"""Detect content type from headers or data."""
if "Content-Type" in headers:
return headers["Content-Type"]
if "content-type" in headers:
return headers["content-type"]
if data:
try:
json.loads(data)
return "application/json"
except (json.JSONDecodeError, TypeError):
pass
return "application/x-www-form-urlencoded"
@register_generator("go")
def generate_go(parsed: ParsedCurl) -> str:
"""Generate Go net/http code from parsed curl data."""
lines = []
lines.append("package main")
lines.append("")
lines.append("import (")
lines.append(' "bytes"')
lines.append(' "fmt"')
lines.append(' "net/http"')
lines.append(' "strings"')
lines.append(")")
lines.append("")
lines.append("func main() {")
lines.append(f' url := {repr(parsed.url)}')
lines.append("")
headers = dict(parsed.headers) if parsed.headers else {}
if parsed.user_agent and "User-Agent" not in headers and "user-agent" not in headers:
headers["User-Agent"] = parsed.user_agent
if parsed.auth:
auth_str = f"{parsed.auth[0]}:{parsed.auth[1]}"
encoded = ""
for _, c := range auth_str {
encoded += string(c)
}
headers["Authorization"] = f"Basic " + encoded
method = parsed.method
body := ""
if parsed.data:
content_type = _detect_content_type(headers, parsed.data)
body = repr(parsed.data)
if content_type == "application/json":
try:
json_data = json.loads(parsed.data)
body = "strings.NewReader(" + repr(json.dumps(json_data)) + ")"
headers["Content-Type"] = "application/json"
except (json.JSONDecodeError, TypeError):
body = "strings.NewReader(" + repr(parsed.data) + ")"
else:
body = "strings.NewReader(" + repr(parsed.data) + ")"
if method == "GET":
method = "POST"
if headers:
lines.append(" req, err := http.NewRequest(" + repr(method) + ", url, " + body + ")")
lines.append(" if err != nil {")
lines.append(" panic(err)")
lines.append(" }")
lines.append("")
for k, v in headers.items():
lines.append(f' req.Header.Add({repr(k)}, {repr(v)})')
else:
lines.append(" req, err := http.NewRequest(" + repr(method) + ", url, " + body + ")")
lines.append(" if err != nil {")
lines.append(" panic(err)")
lines.append(" }")
lines.append("")
lines.append(" client := &http.Client{}")
lines.append(" resp, err := client.Do(req)")
lines.append(" if err != nil {")
lines.append(" panic(err)")
lines.append(" }")
lines.append(" defer resp.Body.Close()")
lines.append("")
lines.append(" fmt.Println(resp.Status)")
lines.append("}")
return "\n".join(lines)