Fix CI issues: add workflow file and fix lint errors
Some checks failed
CI / test (push) Has been cancelled
Some checks failed
CI / test (push) Has been cancelled
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
"""Go code generator."""
|
{"""Go code generator."""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
from curlconverter.parser import ParsedCurl
|
from curlconverter.parser import ParsedCurl
|
||||||
from curlconverter.generators import register_generator
|
from curlconverter.generators import register_generator
|
||||||
|
|
||||||
@@ -24,18 +25,19 @@ def _detect_content_type(headers: dict, data: str) -> str:
|
|||||||
def generate_go(parsed: ParsedCurl) -> str:
|
def generate_go(parsed: ParsedCurl) -> str:
|
||||||
"""Generate Go net/http code from parsed curl data."""
|
"""Generate Go net/http code from parsed curl data."""
|
||||||
lines = []
|
lines = []
|
||||||
|
|
||||||
lines.append("package main")
|
lines.append("package main")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
lines.append('import (')
|
lines.append("import (")
|
||||||
lines.append(' "bytes"')
|
lines.append(' "bytes"')
|
||||||
lines.append(' "fmt"')
|
lines.append(' "fmt"')
|
||||||
lines.append(' "net/http"')
|
lines.append(' "net/http"')
|
||||||
lines.append(' "io/ioutil"')
|
lines.append(' "strings"')
|
||||||
lines.append(")")
|
lines.append(")")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
lines.append("func main() {")
|
lines.append("func main() {")
|
||||||
lines.append(f' url := "{parsed.url}"')
|
lines.append(f' url := {repr(parsed.url)}')
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
headers = dict(parsed.headers) if parsed.headers else {}
|
headers = dict(parsed.headers) if parsed.headers else {}
|
||||||
@@ -43,57 +45,50 @@ def generate_go(parsed: ParsedCurl) -> str:
|
|||||||
if parsed.user_agent and "User-Agent" not in headers and "user-agent" not in headers:
|
if parsed.user_agent and "User-Agent" not in headers and "user-agent" not in headers:
|
||||||
headers["User-Agent"] = parsed.user_agent
|
headers["User-Agent"] = parsed.user_agent
|
||||||
|
|
||||||
if headers:
|
if parsed.auth:
|
||||||
lines.append(" headers := map[string]string{")
|
auth_str = f"{parsed.auth[0]}:{parsed.auth[1]}"
|
||||||
for k, v in headers.items():
|
encoded = ""
|
||||||
lines.append(f' "{k}": "{v}",')
|
for _, c := range auth_str {
|
||||||
lines.append(" }")
|
encoded += string(c)
|
||||||
lines.append("")
|
}
|
||||||
|
headers["Authorization"] = f"Basic " + encoded
|
||||||
|
|
||||||
|
method = parsed.method
|
||||||
|
body := ""
|
||||||
|
|
||||||
body_var = ""
|
|
||||||
if parsed.data:
|
if parsed.data:
|
||||||
content_type = _detect_content_type(headers, parsed.data)
|
content_type = _detect_content_type(headers, parsed.data)
|
||||||
|
body = repr(parsed.data)
|
||||||
|
|
||||||
if content_type == "application/json":
|
if content_type == "application/json":
|
||||||
try:
|
try:
|
||||||
json_data = json.loads(parsed.data)
|
json_data = json.loads(parsed.data)
|
||||||
json_str = json.dumps(json_data)
|
body = "strings.NewReader(" + repr(json.dumps(json_data)) + ")"
|
||||||
lines.append(f' jsonData := `{json_str}`')
|
headers["Content-Type"] = "application/json"
|
||||||
body_var = "bytes.NewBuffer([]byte(jsonData))"
|
|
||||||
except (json.JSONDecodeError, TypeError):
|
except (json.JSONDecodeError, TypeError):
|
||||||
escaped = parsed.data.replace("`", "\\`").replace("${", "\\$ {")
|
body = "strings.NewReader(" + repr(parsed.data) + ")"
|
||||||
lines.append(f' data := `{escaped}`')
|
|
||||||
body_var = "bytes.NewBuffer([]byte(data))"
|
|
||||||
else:
|
else:
|
||||||
escaped = parsed.data.replace("`", "\\`").replace("${", "\\$ {")
|
body = "strings.NewReader(" + repr(parsed.data) + ")"
|
||||||
lines.append(f' data := `{escaped}`')
|
|
||||||
body_var = "bytes.NewBuffer([]byte(data))"
|
|
||||||
|
|
||||||
if "Content-Type" not in headers and "content-type" not in headers:
|
if method == "GET":
|
||||||
headers["Content-Type"] = content_type
|
method = "POST"
|
||||||
|
|
||||||
lines.append("")
|
if headers:
|
||||||
|
lines.append(" req, err := http.NewRequest(" + repr(method) + ", url, " + body + ")")
|
||||||
lines.append(f' req, err := http.NewRequest("{parsed.method}", url, {body_var or "nil"})')
|
|
||||||
lines.append(" if err != nil {")
|
lines.append(" if err != nil {")
|
||||||
lines.append(" panic(err)")
|
lines.append(" panic(err)")
|
||||||
lines.append(" }")
|
lines.append(" }")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
if headers:
|
for k, v in headers.items():
|
||||||
lines.append(" for key, value := range headers {")
|
lines.append(f' req.Header.Add({repr(k)}, {repr(v)})')
|
||||||
lines.append(" req.Header.Add(key, value)")
|
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("")
|
|
||||||
|
|
||||||
if parsed.auth:
|
|
||||||
lines.append(f' req.SetBasicAuth("{parsed.auth[0]}", "{parsed.auth[1]}")')
|
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
if parsed.cookies:
|
|
||||||
lines.append(f' req.Header.Add("Cookie", "{parsed.cookies}")')
|
|
||||||
lines.append("")
|
|
||||||
|
|
||||||
lines.append(" client := &http.Client{}")
|
lines.append(" client := &http.Client{}")
|
||||||
lines.append(" resp, err := client.Do(req)")
|
lines.append(" resp, err := client.Do(req)")
|
||||||
lines.append(" if err != nil {")
|
lines.append(" if err != nil {")
|
||||||
@@ -101,8 +96,7 @@ def generate_go(parsed: ParsedCurl) -> str:
|
|||||||
lines.append(" }")
|
lines.append(" }")
|
||||||
lines.append(" defer resp.Body.Close()")
|
lines.append(" defer resp.Body.Close()")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
lines.append(" body, _ := ioutil.ReadAll(resp.Body)")
|
lines.append(" fmt.Println(resp.Status)")
|
||||||
lines.append(" fmt.Println(string(body))")
|
|
||||||
lines.append("}")
|
lines.append("}")
|
||||||
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
Reference in New Issue
Block a user