Created
September 21, 2020 05:49
-
-
Save Aragroth/a6b5c252ea3072c83a2d005db6c918aa to your computer and use it in GitHub Desktop.
This file contains hidden or 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 main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| "golang.org/x/crypto/acme/autocert" | |
| "log" | |
| "github.com/rs/cors" | |
| "net/http" | |
| ) | |
| //var ctx, cancel = context.Background() | |
| func main() { | |
| mux := http.NewServeMux() | |
| mux.HandleFunc("/send/", analyticsHandler) | |
| corsMiddleware := cors.New(cors.Options{ | |
| AllowedOrigins: []string{"https://locatlhost"}, | |
| }) | |
| handler := corsMiddleware.Handler(mux) | |
| log.Fatal( | |
| http.Serve(autocert.NewListener("localhsot"), handler), | |
| http.ListenAndServe(":8000", mux), | |
| ) | |
| } | |
| type analyticsData struct { | |
| HitType string `json:"hit_type"` | |
| //PageType string `json:"page_type"` | |
| //EventCategory string `json:"event_category"` | |
| } | |
| type unseccessfulJSONResponse struct { | |
| Success bool `json:"success"` | |
| ErrorMessage string `json:"errorMessage"` | |
| } | |
| type successfulJSONResponse struct { | |
| Success bool `json:"success"` | |
| Message string `json:"errorMessage"` | |
| } | |
| func writeUnsuccessfulResponse(w http.ResponseWriter, errMessage string) { | |
| response, _ := json.Marshal(&unseccessfulJSONResponse{ | |
| Success: false, | |
| ErrorMessage: errMessage, | |
| }) | |
| w.WriteHeader(http.StatusBadRequest) | |
| _, ok := w.Write(response) | |
| if ok != nil { | |
| fmt.Println("some error accured") | |
| } | |
| } | |
| func writeSuccessfulResponse(w http.ResponseWriter, message string) { | |
| w.WriteHeader(http.StatusOK) | |
| var ok error | |
| if message == "" { | |
| _, ok = w.Write([]byte(`{"success": true}`)) | |
| } else { | |
| response, _ := json.Marshal(&successfulJSONResponse{ | |
| Success: true, | |
| Message: message, | |
| }) | |
| _, ok = w.Write(response) | |
| } | |
| if ok != nil { | |
| fmt.Println("some error accured") | |
| } | |
| } | |
| func ProcessPageView() { | |
| fmt.Println("Page Asked") | |
| } | |
| func analyticsHandler(w http.ResponseWriter, r *http.Request) { | |
| w.Header().Set("Content-Type", "application/json; charset=utf-8") | |
| decoder := json.NewDecoder(r.Body) | |
| var analyticsData analyticsData | |
| err := decoder.Decode(&analyticsData) | |
| fmt.Println(analyticsData) | |
| if err != nil { | |
| writeUnsuccessfulResponse(w, "Can not parse JSON: " + err.Error()) | |
| return | |
| } | |
| if analyticsData.HitType == "page-view" { | |
| ProcessPageView() | |
| writeSuccessfulResponse(w, "") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment