Created
May 6, 2020 10:46
-
-
Save ibrunotome/7a0ccc572cc48693aab80523b8a8874b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package p | |
import ( | |
"encoding/json" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
) | |
type response struct { | |
Data interface{} `json:"data"` | |
Meta interface{} `json:"meta"` | |
} | |
type timestamp struct { | |
Timestamp int64 `json:"timestamp"` | |
} | |
// APIProxy method will proxy all api requests to the api service | |
func APIProxy(w http.ResponseWriter, r *http.Request) { | |
url := os.Getenv("API_HOST") + r.URL.String() | |
proxyRequest, err := http.NewRequest(r.Method, url, r.Body) | |
if err != nil { | |
log.Println(err) | |
respondWithError(w, 500, "Internal Server Error!") | |
return | |
} | |
proxyRequest.Header.Add("Host", r.Host) | |
proxyRequest.Header.Add("X-Forwarded-For", r.RemoteAddr) | |
for header, values := range r.Header { | |
for _, value := range values { | |
proxyRequest.Header.Set(header, value) | |
} | |
} | |
proxyResponse, err := http.DefaultClient.Do(proxyRequest) | |
if err != nil { | |
log.Println(err) | |
respondWithError(w, 500, "Internal Server Error!") | |
return | |
} | |
body, err := ioutil.ReadAll(proxyResponse.Body) | |
if err != nil { | |
log.Println(err) | |
respondWithError(w, 500, "Internal Server Error!") | |
return | |
} | |
for header, values := range proxyResponse.Header { | |
for _, value := range values { | |
w.Header().Set(header, value) | |
} | |
} | |
w.Header().Del("Accept-Ranges") | |
w.Header().Del("Via") | |
w.Write(body) | |
} | |
func respondWithError(w http.ResponseWriter, code int, message string) { | |
respondWithCustomData(w, code, map[string]string{"message": message}) | |
} | |
func respondWithCustomData(w http.ResponseWriter, code int, data interface{}) { | |
response, err := json.Marshal(response{ | |
Data: data, | |
Meta: timestamp{ | |
Timestamp: time.Now().UTC().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond)), | |
}, | |
}) | |
if err != nil { | |
log.Println(err) | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write([]byte("500 - Internal Server Error!")) | |
} | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(code) | |
w.Write(response) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment