read network logs in go

To read network logs in Go, you can use the net/http package along with the log package. Here's a simple example:

main.go
package main

import (
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	// Start a simple HTTP server
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Read the request body
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// Log the request details
		log.Printf("Received request: Method=%s, Path=%s, Body=%s", r.Method, r.URL.Path, string(body))

		// Send a response
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Hello, World!"))
	})

	// Start the server
	log.Fatal(http.ListenAndServe(":8080", nil))
}
621 chars
30 lines

In this example, we start an HTTP server that listens on port 8080. Whenever a request is made to the server, we log the request details using the log package's Printf function. You can customize the log format and output as per your requirements by modifying the log message.

related categories

gistlibby LogSnag