how to call graphql resolver inside go code - go

I tried this code
url := "http://142.77.221.41:8000/graphql"
query := `{
hello(theme:"HELLO WORLD", html: "<h1>hello</h1>", recipientList: "hello#mail.ua") {theme, html, recipientList}
}`
body := strings.NewReader(`{"query":` + query + `}`)
//json := `{"query":` + strconv.QuoteToASCII(query) + `}`
req, err := http.NewRequest("POST", url, body)
if err != nil {
fmt.Println(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
fmt.Println(resp.Status)
it sends
500 Internal Server Error
but when I go to the http://142.77.221.41:8000/graphql and type the same query on playground it works fine

Related

how to set headers that get from client api in Go

I have a client API where the client API has headers:
req.Header.Set("Authorization", tokenBarear)
req.Header.Add("Content-Type", "application/json")
for token bearer which is set for the time limit.
However when I run and test in postman it returns an error; so what's wrong with my code?
When I print using the following code tokenBarear := ctx.Get("Authorization")
generate correct token however when i call in headers using this
req.Header.Set("Authorization", tokenBarear)
req.Header.Add("Content-Type", "application/json")
the result is an error
client := &http.Client{}
jsonData, err := json.Marshal(params)
if err != nil {
return nil, exception.JSONParseExceptionMessage
}
payload := strings.NewReader(string(jsonData))
req, err := http.NewRequest("POST", repository.Configuration.Get("FLOW_URL_STAGING")+"/v2/inquiry", payload)
if err != nil {
return nil, fmt.Errorf("url issue")
}
cashinResponse := &response.CashinResponse{}
tokenBarear := ctx.Get("Authorization")
// contentType := ctx.Get("Content-Type")
req.Header.Set("Authorization", tokenBarear)
req.Header.Add("Content-Type", "application/json")
fmt.Println("tokens", tokenBarear)
// fmt.Println("content -type", contentType)
res, err := client.Do(req)
if err != nil {
fmt.Println("error disini", err)
return nil, err
}
json.NewDecoder(res.Body).Decode(&cashinResponse)
defer res.Body.Close()
fmt.Println("==============")
fmt.Println("Repository weblinking :", cashinResponse)
fmt.Println("==============")
return cashinResponse, nil

How to read from array json response in Go

I have an API request that returns a refresh_token inside array, which looks something like this:
[
{
"refresh_token" : "C61551CEA183EDB767AA506926F423B339D78E2E2537B4AC7F8FEC0C29988819"
}
]
I need to access this refresh_token's value, and use it to query another API.
To do this, I'm attempting to first 'ReadAll' the response body, and then access the key inside of it by calling 'refreshToken'.
However, it's not working. Does anyone know how to resolve this as I can't figure it out?
Here's my code:
func Refresh(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
// q := url.Values{}
fetchUrl := "https://greatapiurl.com"
req, err := http.NewRequest("GET", fetchUrl, nil)
if err != nil {
fmt.Println("Errorrrrrrrrr")
os.Exit(1)
}
req.Header.Add("apikey", os.Getenv("ENV"))
req.Header.Add("Authorization", "Bearer "+os.Getenv("ENV"))
resp, err := client.Do(req)
if err != nil {
fmt.Println("Ahhhhhhhhhhhhh")
os.Exit(1)
}
respBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println(respBody["refresh_token"])
w.WriteHeader(resp.StatusCode)
w.Write(respBody)
}
If you do not need it as custom type you can cast it as []map[string]string
respBody, _ := ioutil.ReadAll(resp.Body)
var body []map[string]string
json.Unmarshal(respBody, &body)
fmt.Println(body[0]["refresh_token"])

Golang API Post upload file

I'm new to golang and I'm trying to write a function that uploads a file with a post request to API server. I try Post API in Postman, it is OK but in my code I have some error like this image
This is my golang code:
func (c *Client) PostUploadFile(endpoint string, params map[string]string) []byte {
url := "/examples/image/text.txt"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Open the file
file, err := os.Open(url)
if err != nil {
// return nil, err
}
// Close the file later
defer file.Close()
part, err := writer.CreateFormFile("file", filepath.Base(url))
_, err = io.Copy(part, file)
if err != nil {
fmt.Println(err)
// return nil, err
}
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
// return nil, err
}
fmt.Println("Data request:")
fmt.Println(body)
fmt.Println("Endpoint:")
fmt.Println(c.BaseUrl + endpoint)
req, requestErr := http.NewRequest("POST", c.BaseUrl+endpoint, body)
if requestErr != nil {
log.Fatalln(requestErr)
}
req.Header.Add("auth_token", c.AuthToken)
req.Header.Add("accept", "application/json")
// req.Header.Add("Content-Type", "application/json")
req.Header.Add("Content-Type", writer.FormDataContentType())
client := &http.Client{}
fmt.Println("Response:")
resp, err := client.Do(req)
fmt.Println(resp)
if err != nil {
log.Println(err)
return []byte(``)
}
return c.parseBody(resp)
}
and this is a param formdata in body:
fmt.Printf("%+v\n", c.UploadImage(map[string]string{
"file": "/examples/image/text.txt",
"wfs_id": "30578",
"id": "59284",
"element_id": "119726",
}))

How to GET Request with Cookie After login

I tried to get some resp.Body of jadwalURL. jadwalURL can be access after login, so I add the Cookie header to the request. But Sadly the response is not quite that I want (response is home page). I tried this similiar flow with Postman. and I got the jadwalURL body as i wanted. Is there anything wrong with my code? I still dont get the solution after 3 hours searching.
func main() {
data := url.Values{}
data.Set("username", username)
data.Set("password", password)
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, loginURL, strings.NewReader(data.Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, _ := client.Do(r)
cookie := resp.Cookies()
fmt.Println(cookie)
fmt.Println(resp.Status)
req, err := http.NewRequest(http.MethodGet, jadwalURL, nil)
if err != nil {
panic(err)
}
req.AddCookie(&http.Cookie{
Name: cookie[0].Name,
Value: cookie[0].Value,
Domain: domainURL,
Path: "/",
})
jadwalResp, err := http.DefaultClient.Do(req)
if err != nil {
panic(nil)
}
body, _ := ioutil.ReadAll(jadwalReq.Body)
jadwalResp.Body.Close()
fmt.Println(string(body))
}
Hi If you have this problem I just change create a newClient the problem is i tried to make request with client.
newClient := &http.Client{}
// then
jadwalResp, err := newClient.Do(req)

How can I resolve 400 status code by sending POST in Golang?

I have Python script, that works fine
def register():
url = prime_url + '/v2/mobile/user/register?lang=ru'
payload = {
'email' : 'test#test.test.mail.com',
'deviceId' : 'testId',
'password' : 'Test1234'
}
response = requests.post(url, data = payload)
print(response.text)
Response:
{"success":true,"data":"SUCCESS_FIRST_STAGE_REGISTER","params":"Two-factor authentication code sent to test#testtest.test.mail.com","code":200,"runTime":2.391624927520752}
I wrote code on Golang:
func postRequest(target string, params string) {
var jsonStr = []byte(`{"email":"testtestetetsees#mail.ru", "deviceId":"ftefst891", "password":"qwertyQwerty132"}`)
req, err := http.NewRequest("POST", target, bytes.NewBuffer(jsonStr))
if err != nil {
log.Fatalln(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
}
Response:
map[code:400 data:ERROR_VALIDATE params:map[deviceId:[Device Id cannot be blank.] email:[Email cannot be blank.] password:[Password cannot be blank.]] runTime:0.023465871810913086 success:false]
I see that problem is by sending JSON string. What should I do?
As mentioned by Peter in the comments you can use PostForm once you convert the data into url.Values.
If the server expects content in urlencoded form but the input you have is json you'll have to convert it first.
var data = []byte(`{"email":"testtestetetsees#mail.ru", "deviceId":"ftefst891", "password":"qwertyQwerty132"}`)
m := map[string]string{}
if err := json.Unmarshal(data, &m); err != nil {
panic(err)
}
v := url.Values{}
for key, val := range m {
v.Add(key, val)
}
resp, err := http.PostForm("https://example.com", v)
if err != nil {
panic(err)
}
// ...
If the input you have is already in urlencoded form but it needs escaping you can parse it using url.ParseQuery and let the result of that do the escaping.
var data = "email=testtestetetsees#mail.ru&deviceId=ftefst891&password=qwertyQwerty132"
v, err := url.ParseQuery(data)
if err != nil {
panic(err)
}
resp, err := http.PostForm("https://example.com", v)
if err != nil {
panic(err)
}
// ...
Mention content type as "application/json"
For simplicity you can use http.Post, use the below code as a example:
resp, err := http.Post(target, "application/json", bytes.NewBuffer([]byte("{\"email\":\"testtestetetsees#mail.ru\", \"deviceId\":\"ftefst891\", \"password\":\"qwertyQwerty132\"}")))

Resources