I m actually learning golang and try to implement a proxy on a an Rest API that I've made in another language
For now, I only want to query my golang API, extract they actual path parameters and query the other API based on it.
I want the result to be "exactly" the same (or at least, the body part), just like a simple JSON.
For now, I don't want to create a structure for my data, I just want to simply get and retrieve the content.
Here's what I have:
package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) const API_URL string = "https://my-api-path/" func setHeaders(w http.ResponseWriter) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") } func extractParams(r *http.Request) map[string]string { return mux.Vars(r) } func getHandler(w http.ResponseWriter, r *http.Request) { setHeaders(w) params := extractParams(r) url := API_URL + params["everything"] response, err := http.Get(url) if err != nil { fmt.Fprint(w, err) } fmt.Fprint(w, response) } func main() { router := mux.NewRouter() router.HandleFunc("/{everything}", getHandler) http.ListenAndServe(":8080", router) } My problem
For now, I m not able to retrieve JSON information from my other API. I only have a text/plain Content-Type which is weird since I enforce application/json and I only have some header details in the response body, something like:
&{200 OK 200 HTTP/2.0 2 0 map[Allow:[GET, HEAD, OPTIONS] Expect-Ct:[max-age=86400, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"] Server:[cloudflare] Cf-Ray:[some-ray] Date:[Tue, 12 Jun 2018 14:38:57 GMT] Content-Type:[application/json] Set-Cookie:[__cfduid=lolol; expires=Wed, 12-Jun-19 14:38:56 GMT; path=/; domain=some-domain; HttpOnly; Secure] Vary:[Accept-Encoding Cookie] X-Frame-Options:[SAMEORIGIN] X-Xss-Protection:[1; mode=block]] 0xc4201926f0 -1 [] false true map[] 0xc420150800 0xc4200e8370} Do you have any idea on how I can proxy this request (or the JSON result) ?
io.Copy(w, response.Body). And please do close the response body i.e.defer response.Body.Close(). Also when Get returns an error and you write it to the reponse there is no reason to also write a nil response, so add a return statement to the end of theif err != nil ...conditional's body.