feat: simplify echo, add handling of json content type, optimize request counter

This commit is contained in:
Tom Andrade 2023-01-26 11:45:29 +01:00
parent 04792d0b5e
commit d10e8c866b
Signed by: wolvie
GPG Key ID: 31AAB07872E82669

25
main.go
View File

@ -3,6 +3,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"log" "log"
"net/http" "net/http"
"os" "os"
@ -74,16 +75,26 @@ func serve(l int) bool {
// handler generates the echo server response // handler generates the echo server response
func handler(l int) http.HandlerFunc { func handler(l int) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
r.ParseForm() defer C.Add()
jm, err := json.Marshal(r.PostForm) if !serve(l) {
if err != nil || !serve(l) {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "why did you do that?")
C.Add()
return return
} }
fmt.Fprintf(w, "%v", string(jm)) if r.Header.Get("Content-Type") == "application/json" {
C.Add() v := make(map[string]interface{})
err := json.NewDecoder(r.Body).Decode(&v)
if err != nil {
http.Error(w, "why did you do that?", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s", v)
return
}
v, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading body", http.StatusBadRequest)
}
fmt.Fprintf(w, "%s", v)
} }
} }