Skip to content

Instantly share code, notes, and snippets.

@uberswe
Last active September 9, 2020 21:03
Show Gist options
  • Save uberswe/e93b9967853a55b5b5fcde9cd0ee1eaf to your computer and use it in GitHub Desktop.
Save uberswe/e93b9967853a55b5b5fcde9cd0ee1eaf to your computer and use it in GitHub Desktop.
package vgs
import (
"html/template"
"io/ioutil"
"log"
"net/http"
)
// Run runs the application and sets up the relevant routes
func Run() {
var err error
http.HandleFunc("/", index)
http.HandleFunc("/post", inbound)
log.Println("listening on :8080")
err = http.ListenAndServe(":8080", nil)
checkError(err)
}
// index simply loads the HTML form which communicates with VGS
func index(w http.ResponseWriter, r *http.Request) {
log.Println("index")
log.Printf("type: %s\n", r.Method)
log.Printf("host: %s\n", r.Host)
log.Printf("ip: %s\n", r.RemoteAddr)
log.Printf("url: %s\n", r.URL.Path)
if r.URL.Path != "/" {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte("{}"))
checkError(err)
return
}
var err error
t := template.Must(template.ParseFiles("tmpl/form.html"))
err = t.Execute(w, nil)
checkError(err)
}
// inbound proxy for vgs requests. The data sent via the HTML form should be received here.
func inbound(w http.ResponseWriter, r *http.Request) {
setupResponse(&w, r)
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
log.Println("inbound proxy request")
log.Printf("type: %s\n", r.Method)
log.Printf("host: %s\n", r.Host)
log.Printf("url: %s\n", r.URL)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v\n", err)
http.Error(w, "can't read body", http.StatusBadRequest)
return
}
log.Printf("body: %v\n", string(body))
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(body)
checkError(err)
}
func setupResponse(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// checkError is the general error handler for vgs
func checkError(e error) {
if e != nil {
log.Fatal(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment