Basic HTTP Auth in Go - go

I'm trying to do basic HTTP auth with the code below, but it is throwing out the following error:
2013/05/21 10:22:58 Get mydomain.example: unsupported protocol scheme ""
exit status 1
func basicAuth() string {
var username string = "foo"
var passwd string = "bar"
client := &http.Client{}
req, err := http.NewRequest("GET", "mydomain.example", nil)
req.SetBasicAuth(username, passwd)
resp, err := client.Do(req)
if err != nil{
log.Fatal(err)
}
bodyText, err := ioutil.ReadAll(resp.Body)
s := string(bodyText)
return s
}
Any idea what I may be doing wrong?

the potential 'gotcha' is if your website does any redirects... Go-lang will drop your specified headers on the redirects. (I had to do wireshark to see this! You can quicky find out in chrome by right-clicking then "inspect element" and click network tab)
you'll want to define a redirect function that adds the header back in.
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
func redirectPolicyFunc(req *http.Request, via []*http.Request) error{
req.Header.Add("Authorization","Basic " + basicAuth("username1","password123"))
return nil
}
func main() {
client := &http.Client{
Jar: cookieJar,
CheckRedirect: redirectPolicyFunc,
}
req, err := http.NewRequest("GET", "http://localhost/", nil)
req.Header.Add("Authorization","Basic " + basicAuth("username1","password123"))
resp, err := client.Do(req)
}

You need to specify the protocol for NewRequest, e.g. "http://", see here.
req, err := http.NewRequest("GET", "http://mydomain.example", nil)

Related

Include client multi part form file in new POST request

Think I might be missing something obvious here. I'm attempting to grab the file from a client request hitting my server and forwarding that to an external API for processing by creating a new multipart request and copying the file over. In this case, the API is looking for a FormFile under the "files" key. The receiving API keeps telling me the file has invalid mime type application/octet-stream
API Call Documentation
func forwardFile(r *http.Request) (string, error) {
file, fileHandler, err := r.FormFile("image")
if err != nil {
return "", err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("files", fileHandler.Filename)
if err != nil {
return "", err
}
if _, err := io.Copy(part, file); err != nil {
return "", err
}
writer.Close()
req, _ := http.NewRequest("POST", newUploadUrl, body)
req.Header.Add("Content-Type", writer.FormDataContentType())
client := &http.Client{}
response, err := client.Do(req)
}
Thank you for your time.
I guess you need to change your content type to multipart/form-data
Solved it by creating a MIMEHeader and populating the disposition and content type myself, see below:
partHeader := textproto.MIMEHeader{}
disposition := fmt.Sprintf("form-data; name=\"files\"; filename=\"%s\"", fileHandler.Filename)
partHeader.Add("Content-Disposition", disposition)
partHeader.Add("Content-Type", "image/png")
part, err := writer.CreatePart(partHeader)
if _, err := io.Copy(part, file); err != nil {
log.Print("Error copying")
return "", err
}

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"])

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)

Migrating your App Engine app from Go 1.9 to Go 1.11

I have update my golang version from 1.9 to 1.11. After updating sendgrid mail send not working.
I have followed below link:
https://cloud.google.com/appengine/docs/standard/go111/go-differences
and found that we need to Use request.Context() or your preferred context instead of using appengine.NewContext .
But when I am trying request.Context() getting request is not defined.
So how to change appengine.NewContext to request.Context() for go111
Here is my code:
func SendTestmail(c echo.Context) error {
type output struct {
Message string `json:"message"`
Status bool `json:"status"`
}
result := output{}
//mail code
to := "myemail#mail.com"
firstName := c.FormValue("first_name")
subject := "Send Test mail"
msg := "Dear User , " + "\n \n" +
"You have successfully Tested." + "\n " +
"Sincerely, " + "\n \n" +
"Team"
var Body = general.FrameEmailObj(os.Getenv("SENDGRID_SENDER"), subject, to, msg)
url := os.Getenv("SENDGRID_URL")
req, err := http.NewRequest("POST", url, bytes.NewBuffer(Body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("SENDGRID_API_KEY"))
req.Header.Set("Content-Type", "application/json")
ctx := appengine.NewContext(c.Request())
client := urlfetch.Client(ctx)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
//end mail code
result.Message = "send mail success."
return c.JSON(http.StatusUnauthorized, result)
}
I am getting below error in appengine:-
PANIC RECOVER Post https://api.sendgrid.com/v3/mail/send: not an App Engine context goroutine
Thanks in advance for your help.
The migration document states that App Engine specific uflfetch package is superseded by the net/http package.
Replace this code:
ctx := appengine.NewContext(c.Request())
client := urlfetch.Client(ctx)
resp, err := client.Do(req)
with:
resp, err := http.DefaultClient.Do(req)

how to call graphql resolver inside go code

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

Resources