mfrachet
mfrachet

Reputation: 8922

Proxying a REST API using golang

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) ?

Upvotes: 3

Views: 2151

Answers (1)

eugenioy
eugenioy

Reputation: 12393

About the Content-Type header not being written to your response:

Seems to be expected due to the order in which you are performing these operations:

w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")

See here: https://golang.org/pkg/net/http/#ResponseWriter

Changing the header map after a call to WriteHeader (or Write) has no effect unless the modified headers are trailers.

Try inverting those to read:

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)

Upvotes: 5

Related Questions