I have a handler that does one thing if its a post and another if its a get but for some reason it is always a GET. I’ve made my own clients and ran them concurrently and I’ve also started the server and issued curl still no matter what I do inside the handler its a GET.
Am I thinking of handlers incorrectly could It have to do something with the default serve mux
I dont want to use 3rd party muxers I just want standard library to work… I took out some code so I wont get fired or something thank you for your time and help it is very appreciated
import (
"net/http"
"path"
"encoding/json"
"fmt"
"time"
"log"
"io/ioutil"
)
func testHandler(w http.ResponseWriter, r *http.Request) {
switch method := r.Method; method{
case "GET":
var accountName = path.Base(r.URL.String())
var response interface{}
if accountName == "false" {
response = failure{
ErrorCode: "418",
ErrorMessage: "I'm a teapot",
}
}
excludeResponseJson, err := json.MarshalIndent(response,""," ")
if err != nil {
fmt.Fprintf(w, "Error: %s", err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(excludeResponseJson)
case "POST":
log.Fatal("why doesnt this work as a post ")
}
}
func server() {
http.HandleFunc("/test/", testHandler)
http.ListenAndServe(":3000", nil)
}
func main() {
server()
// client()
}
func client() {
client := &http.Client{}
req := ask("GET", "test/accountName")
clientDo(client,req, "consent success ")
req = ask("GET", "test/false")
clientDo(client,req, "consent failure ")
}
func clientDo(client *http.Client, req *http.Request , responseType string) {
resp, err := client.Do(req)
errorHandler(err)
body, err := ioutil.ReadAll(resp.Body)
fmt.Println( responseType + "Response: \n", string(body))
resp.Body.Close()
}
func ask(method string, path string) *http.Request {
req, _ := http.NewRequest(method, "http://localhost:3000/" + path, nil)
req.Header.Set("Content-Type", "application/json")
return req
}
func errorHandler(err error) {
if err != nil {
log.Fatal(err)
}
}
// general error object
type failure struct {
ErrorCode string `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
}