Skip to content

Instantly share code, notes, and snippets.

@wyattjoh
Last active December 8, 2022 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyattjoh/1107dae880d66c2963b4ed4366f5bc31 to your computer and use it in GitHub Desktop.
Save wyattjoh/1107dae880d66c2963b4ed4366f5bc31 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"os"
)
func main() {
filename := flag.String("file", "logs.json", "file to append logs that is send to this server")
addr := flag.String("address", "127.0.0.1:8081", "address for the server to bind to")
flag.Parse()
// Open the logs file for appending (create it if it does not exist).
f, err := os.OpenFile(*filename, os.O_APPEND|os.O_WRONLY, 0666)
if err != nil {
if !os.IsNotExist(err) {
log.Fatalf("could not open the logs file: %s", err)
}
f, err = os.Create(*filename)
if err != nil {
log.Fatalf("could not create the logs file: %s", err)
}
}
defer f.Close()
// Create the JSON encoder. When objects are encoded into the encoder it
// will write it to the writer (the file in this case) followed by a
// newline.
encoder := json.NewEncoder(f)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
log.Printf("unexpected method: %s", r.Method)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
contentType := r.Header.Get("content-type")
if contentType != "application/json" {
log.Printf("unexpected content type: %s", contentType)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
var packets []map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&packets); err != nil {
log.Printf("could not decode request: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
for _, packet := range packets {
if err := encoder.Encode(packet); err != nil {
log.Printf("could not encode packet: %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusNoContent)
})
log.Printf("listening on %s", *addr)
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatalf("could not listen and serve: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment