Skip to content

Instantly share code, notes, and snippets.

@navigaid
Created December 13, 2017 11:21
Show Gist options
  • Save navigaid/ff4a768c082418c6844bc82426318a37 to your computer and use it in GitHub Desktop.
Save navigaid/ff4a768c082418c6844bc82426318a37 to your computer and use it in GitHub Desktop.
Golang CORS Proxy Server (Example)
package main
import (
"net/http"
"encoding/json"
"github.com/unrolled/render"
)
const (
GITHUB_API_REPOS string = "https://api.github.com/users/wpioneer/repos"
)
type Repos struct {
Name string `json:"name"`
Description string `json:"description"`
}
func getJson(this interface{}, url string) error {
res, err := http.Get(url)
if err != nil {
return err
}
defer res.Body.Close()
return json.NewDecoder(res.Body).Decode(this)
}
func setDefaultHeaders(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET")
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Vary", "Accept-Encoding")
}
func main() {
render := render.New()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
setDefaultHeaders(w)
repos := new([]Repos)
url := GITHUB_API_REPOS
getJson(repos, url)
render.JSON(w, http.StatusOK, repos)
})
http.ListenAndServe(":8000", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment