github.com/prysmaticlabs/prysm@v1.4.4/tools/http-request-sink/main.go (about)

     1  // Package main implements a simple, http-request-sink which writes
     2  // incoming http request bodies to an append-only text file at a specified directory.
     3  package main
     4  
     5  import (
     6  	"bytes"
     7  	"encoding/json"
     8  	"flag"
     9  	"fmt"
    10  	"io/ioutil"
    11  	"log"
    12  	"net/http"
    13  	"os"
    14  	"path/filepath"
    15  	"strconv"
    16  
    17  	"github.com/prysmaticlabs/prysm/shared/params"
    18  )
    19  
    20  func main() {
    21  	port := flag.Int("port", 8080, "port to listen on")
    22  	writeDirPath := flag.String("write-dir", "", "directory to write an append-only file")
    23  	flag.Parse()
    24  	if *writeDirPath == "" {
    25  		log.Fatal("Needs a -write-dir path")
    26  	}
    27  
    28  	// If the file doesn't exist, create it, or append to the file.
    29  	f, err := os.OpenFile(
    30  		filepath.Join(*writeDirPath, "requests.log"),
    31  		os.O_APPEND|os.O_CREATE|os.O_RDWR,
    32  		params.BeaconIoConfig().ReadWritePermissions,
    33  	)
    34  	if err != nil {
    35  		log.Println(err)
    36  	}
    37  	defer func() {
    38  		if err = f.Close(); err != nil {
    39  			log.Fatal(err)
    40  		}
    41  	}()
    42  
    43  	http.HandleFunc("/", func(writer http.ResponseWriter, r *http.Request) {
    44  		reqContent := map[string]interface{}{}
    45  		if err = parseRequest(r, &reqContent); err != nil {
    46  			log.Println(err)
    47  		}
    48  		log.Printf("Capturing request from %s", r.RemoteAddr)
    49  		if err = captureRequest(f, reqContent); err != nil {
    50  			log.Println(err)
    51  		}
    52  	})
    53  	log.Printf("Listening on port %d", *port)
    54  	log.Fatal(http.ListenAndServe(":"+strconv.Itoa(*port), nil))
    55  }
    56  
    57  func captureRequest(f *os.File, m map[string]interface{}) error {
    58  	enc, err := json.Marshal(m)
    59  	if err != nil {
    60  		return err
    61  	}
    62  	_, err = f.WriteString(fmt.Sprintf("%s\n", enc))
    63  	return err
    64  }
    65  
    66  func parseRequest(req *http.Request, unmarshalStruct interface{}) error {
    67  	body, err := ioutil.ReadAll(req.Body)
    68  	if err != nil {
    69  		return err
    70  	}
    71  	if err = req.Body.Close(); err != nil {
    72  		return err
    73  	}
    74  	req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
    75  	return json.Unmarshal(body, unmarshalStruct)
    76  }