import{CodeBuilder as N}from"../../helpers/code-builder.js";import{HTTPSnippet as k}from"../../index.js";import{Lang as R}from"../../helpers/constants.js";import{buildUrlExpression as E,printUrlVariablesDeclarations as O}from"../../helpers/code-helpers.js";import{normalizeMimeType as g}from"../../../../utils.js";import{MediaTypes as l}from"../../../../../constants.js";import{buildGoDeviceAuthorizationCodeSnippet as C}from"../../helpers/device-auth-snippets.js";const t=1;function d(a={},m){return g(a.mimeType)===m}const B=function(a,m,{target:D,client:c}){const i={capitalize:!0,showBoilerplate:!0,checkErrors:!0,printBody:!0,timeout:-1,indent:"  ",...m},h=a.securityOAuth2ExtraCalls?.[0],n=i.checkErrors?"err":"_",u=a.method.toUpperCase(),e=new N({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:i.capitalize,lang:R.GO}),p=()=>{i.checkErrors&&e.push(t,"if err != nil {").push(t+1,"panic(err)").push(t,"}")};if(i.showBoilerplate&&(e.push("package main").blank().push("import (").push(t,'"fmt"'),(i.timeout>0||h?.flowType==="deviceAuthorization")&&e.push(t,'"time"'),h&&e.push(t,'"encoding/json"'),d(a.postData,l.MULTIPART)&&(e.push(t,'"mime/multipart"'),e.push(t,'"io"'),e.push(t,'"bytes"')),(d(a.postData,l.URL_ENCODED)||d(a.securityOAuth2ExtraCalls?.[0]?.postData,l.URL_ENCODED))&&(e.push(t,'"net/url"'),e.push(t,'"strconv"')),(d(a.postData,l.JSON)||d(a.securityOAuth2ExtraCalls?.[0]?.postData,l.JSON))&&e.push(t,'"bytes"'),(a.postData&&!d(a.postData,l.JSON)||h)&&e.push(t,'"strings"'),e.push(t,'"net/http"'),i.printBody&&e.push(t,'"io/ioutil"'),e.push(")").blank().push("func main() {")),Object.keys(a.allHeaders).length&&Object.keys(a.allHeaders).forEach(r=>{a.allHeaders[r]=`"${a.allHeaders[r]}"`}),h){const r="oAuth2",s=i.checkErrors?`${n} := `:"",o=i.capitalize?"Res":"res",f=new k(h).convert(D,c,{...i,printBody:!1,variablesPrefix:r,showBoilerplate:!1});e.push(f).blank(),h.flowType==="deviceAuthorization"?(e.push(t,`var ${r}${o}Body struct {`).push(t+1,"Device_code string").push(t+1,"Interval int64").push(t+1,"Expires_in int64").push(t,"}").push(t,`${s}json.NewDecoder(${r}${o}.Body).Decode(&${r}${o}Body)`).blank(),p(),C(e,{tokenUrl:h.tokenUrl??"YOUR_TOKEN_URL",clientId:h.clientId??"YOUR_CLIENT_ID",level:t}),a.allHeaders.Authorization='"Bearer " + accessToken'):(e.push(t,`var ${r}${o}Body struct {`).push(t+1,"Access_token string").push(t,"}").push(t,`${s}json.NewDecoder(${r}${o}.Body).Decode(&${r}${o}Body)`).blank(),p(),a.allHeaders.Authorization=`"Bearer " + ${r}${o}Body.Access_token`)}if(O(a,e,t),i.timeout>0&&(c=e.var("client"),e.push(t,"%s := http.Client{",c).push(t+1,"Timeout: time.Duration(%s * time.Second),",i.timeout).push(t,"}").blank()),e.push(t,`${e.var("reqUrl")} := ${E(a,e)}`),a.postData){let r;switch(g(a.postData.mimeType)){case l.URL_ENCODED:a.postData.params.length?(e.push(t,"%s := url.Values{}",e.var("data")),a.postData.params.forEach(s=>{e.push(t,'%s.Set("%s", "%s")',e.var("data"),s.name,s.value)}),e.push(t,'%s, %s := http.NewRequest("%s", %s, strings.NewReader(%s.Encode()))',e.var("req"),n,u,e.var("reqUrl"),e.var("data")),a.allHeaders["Content-Length"]=`strconv.Itoa(len(${e.var("data")}.Encode()))`):a.postData.text&&(e.push(t,'%s := "%s"',e.var("data"),a.postData.text),e.push(t,'%s, %s := http.NewRequest("%s", %s, strings.NewReader(%s))',e.var("req"),n,u,e.var("reqUrl"),e.var("data")),a.allHeaders["Content-Length"]=`strconv.Itoa(len(${e.var("data")}))`);break;case l.JSON:r=JSON.stringify(a.postData.jsonObj,null,2).split(`
`).map(s=>i.indent+s).join(`
`).trim(),e.push(t,`var ${e.var("data")} = []byte(\`${r}\`)`),e.push(t,'%s, %s := http.NewRequest("%s", %s, bytes.NewBuffer(%s))',e.var("req"),n,u,e.var("reqUrl"),e.var("data"));break;case l.MULTIPART:if(e.push(t,"%s := &bytes.Buffer{}",e.var("data")).push(t,"writer := multipart.NewWriter(%s)",e.var("data")),a.postData.params&&a.postData.params.length>0)a.postData.params.forEach(s=>{if(!s.fileName&&!s.contentType){e.push(t,'%s, _ := writer.CreateFormField("%s")',e.var(`${s.name}Fw`),s.name).push(t,'_, %s = io.Copy(%s, strings.NewReader("%s"))',n,e.var(`${s.name}Fw`),s.value),p();return}s.fileName&&(e.push(t,'%s, %s = writer.CreateFormFile("%s", "%s")',e.var(`${s.name}Fw`),n,s.name,s.fileName),p())});else if(a.postData.text){const s=a.postData.text,o=s.match(/^--([^\r\n]+)/);if(o){const f=o[1];s.split(new RegExp(`--${f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(y=>y.trim().length>0).forEach(y=>{const w=y.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(w){const v=w[1],$=w[2],b=y.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),q=(b?b[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');$?(e.push(t,'%s, %s = writer.CreateFormFile("%s", "%s")',e.var(`${v}Fw`),n,v,$),p()):(e.push(t,'%s, _ := writer.CreateFormField("%s")',e.var(`${v}Fw`),v).push(t,'_, %s = io.Copy(%s, strings.NewReader("%s"))',n,e.var(`${v}Fw`),q),p())}})}else{e.push(t,"%s := strings.NewReader(%s)",e.var("payload"),JSON.stringify(a.postData.text)).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,u,e.var("reqUrl"),e.var("payload"));break}}e.push(t,"writer.Close()").blank().push(t,"%s := bytes.NewReader(%s.Bytes())",e.var("payload"),e.var("data")).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,u,e.var("reqUrl"),e.var("payload")),a.allHeaders["Content-Type"]="writer.FormDataContentType()";break;default:a.postData.text&&e.push(t,"%s := strings.NewReader(%s)",e.var("payload"),JSON.stringify(a.postData?.text)).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,u,e.var("reqUrl"),e.var("payload"))}}else e.push(t,'%s, %s := http.NewRequest("%s", %s, nil)',e.var("req"),n,u,e.var("reqUrl"));if(Object.getOwnPropertyNames(a.queryObj).length){e.blank().push(t,`${e.var("query")} := ${e.var("req")}.URL.Query()`);for(const r in a.queryObj){const s=a.queryObj[r],f=typeof s=="string"&&/^\[.*\]$/.test(s)?`\`${s}\``:`"${s}"`;e.push(t,`${e.var("query")}.Add("${r}", ${f})`)}e.push(t,`${e.var("req")}.URL.RawQuery = ${e.var("query")}.Encode()`).blank()}if(p(),a.basicAuth){const{username:r,password:s}=a.basicAuth;e.push(t,`%s.SetBasicAuth("${r}", "${s}")`,e.var("req"))}return Object.keys(a.allHeaders).length&&Object.keys(a.allHeaders).forEach(r=>{e.push(t,'%s.Header.Add("%s", %s)',e.var("req"),r,a.allHeaders[r])}),e.push(t,"%s, %s := %s.Do(%s)",e.var("res"),n,c,e.var("req")),p(),i.printBody&&(e.push(t,"defer %s.Body.Close()",e.var("res")).push(t,"%s, %s := ioutil.ReadAll(%s.Body)",e.var("body"),n,e.var("res")),p()),e.blank().push(t,"fmt.Println(%s)",e.var("res")),i.printBody&&e.push(t,"fmt.Println(string(%s))",e.var("body")),i.showBoilerplate&&e.push("}"),e.join()},P={key:"native",title:"NewRequest",link:"http://golang.org/pkg/net/http/#NewRequest",description:"Golang HTTP client request"};var z=B;export{z as default,P as info};
