Created
December 3, 2021 01:08
-
-
Save amir-khassaia/474e1882023aec9eb6fbfd8c5d0e5bf3 to your computer and use it in GitHub Desktop.
Simple GoLang HTTP REST endpoint that dumps request bodies to stdout
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 main | |
import ( | |
"fmt" | |
"io" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
) | |
const path = "logs" | |
const port = 3003 | |
func handleRequests() { | |
fmt.Printf("Listening on: http://:%d/%s\n", port, path) | |
router := mux.NewRouter().StrictSlash(true) | |
router.Methods("POST").Path("/" + path).HandlerFunc(logs) | |
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), router)) | |
} | |
func logs(w http.ResponseWriter, r *http.Request) { | |
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576)) | |
if err != nil { | |
log.Printf("failed to read body, Error : %v\n", err) | |
w.WriteHeader(http.StatusBadRequest) | |
return | |
} | |
_ = r.Body.Close() | |
log.Printf("%s\n", string(body)) | |
} | |
func main() { | |
handleRequests() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment