109 lines
3.6 KiB
Go
109 lines
3.6 KiB
Go
"""Go code generator."""
|
|
|
|
import json
|
|
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(' "io/ioutil"')
|
|
lines.append(")")
|
|
lines.append("")
|
|
|
|
lines.append("func main() {")
|
|
lines.append(f' url := "{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 headers:
|
|
lines.append(" headers := map[string]string{")
|
|
for k, v in headers.items():
|
|
lines.append(f' "{k}": "{v}",')
|
|
lines.append(" }")
|
|
lines.append("")
|
|
|
|
body_var = ""
|
|
if parsed.data:
|
|
content_type = _detect_content_type(headers, parsed.data)
|
|
|
|
if content_type == "application/json":
|
|
try:
|
|
json_data = json.loads(parsed.data)
|
|
json_str = json.dumps(json_data)
|
|
lines.append(f' jsonData := `{json_str}`')
|
|
body_var = "bytes.NewBuffer([]byte(jsonData))"
|
|
except (json.JSONDecodeError, TypeError):
|
|
escaped = parsed.data.replace("`", "\\`").replace("${", "\\$ {")
|
|
lines.append(f' data := `{escaped}`')
|
|
body_var = "bytes.NewBuffer([]byte(data))"
|
|
else:
|
|
escaped = parsed.data.replace("`", "\\`").replace("${", "\\$ {")
|
|
lines.append(f' data := `{escaped}`')
|
|
body_var = "bytes.NewBuffer([]byte(data))"
|
|
|
|
if "Content-Type" not in headers and "content-type" not in headers:
|
|
headers["Content-Type"] = content_type
|
|
|
|
lines.append("")
|
|
|
|
lines.append(f' req, err := http.NewRequest("{parsed.method}", url, {body_var or "nil"})')
|
|
lines.append(" if err != nil {")
|
|
lines.append(" panic(err)")
|
|
lines.append(" }")
|
|
lines.append("")
|
|
|
|
if headers:
|
|
lines.append(" for key, value := range headers {")
|
|
lines.append(" req.Header.Add(key, value)")
|
|
lines.append(" }")
|
|
lines.append("")
|
|
|
|
if parsed.auth:
|
|
lines.append(f' req.SetBasicAuth("{parsed.auth[0]}", "{parsed.auth[1]}")')
|
|
lines.append("")
|
|
|
|
if parsed.cookies:
|
|
lines.append(f' req.Header.Add("Cookie", "{parsed.cookies}")')
|
|
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(" body, _ := ioutil.ReadAll(resp.Body)")
|
|
lines.append(" fmt.Println(string(body))")
|
|
lines.append("}")
|
|
|
|
return "\n".join(lines)
|