package main import ( "fmt" "net/http" ) type MyHandler struct{} func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func main() { myHandler := &MyHandler{} http.Handle("/", myHandler) http.ListenAndServe(":8080", nil) }
package main import ( "encoding/json" "fmt" "log" "net/http" ) type User struct { Name string `json:"name"` Email string `json:"email"` } func main() { http.HandleFunc("/", handleRequest) log.Fatal(http.ListenAndServe(":8080", nil)) } func handleRequest(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { var user User err := json.NewDecoder(r.Body).Decode(&user) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } response, err := json.Marshal(user) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, string(response)) } else { http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) return } }In this example, we define a `User` struct and a function called `handleRequest` that handles incoming requests. The function checks if the request method is POST and then decodes the JSON data into a `User` struct. We then encode the `User` struct back into JSON format and send it back as a response. If the request method is not POST, we return an error. The `http.HandleFunc` function is used to register the `handleRequest` function as the handler for all incoming requests. In conclusion, the go net/http package provides a rich set of tools for building web servers and HTTP clients. The Handler interface is an important part of this package and allows developers to write custom handlers and middleware.