Update README.md

dev
p6b5nefl7 9 months ago
parent 82629ad1b5
commit 789f73cc04

@ -8,41 +8,95 @@ import (
) )
func getRequest(w http.ResponseWriter, r *http.Request) { func getRequest(w http.ResponseWriter, r *http.Request) {
// 这里是你的getRequest函数的实现... switch r.Method {
// 根据请求方法返回不同的JSON响应 case http.MethodGet:
// ...
// 示例对于GET请求返回一个简单的JSON响应
if r.Method == http.MethodGet {
if r.URL.Query().Get("ID") == "" { if r.URL.Query().Get("ID") == "" {
http.Error(w, "ERROR: id is null", http.StatusBadRequest) http.Error(w,"ERROR : id is null",http.StatusBadRequest)
return return
} }
resp := struct { marshal, _ := json.Marshal(struct {
ID string `json:"ID"` ID string `json:"ID"`
Name string `json:"Name"` Name string `json:"Name"`
}{ }{
ID: r.URL.Query().Get("ID"), ID: r.URL.Query().Get("ID"),
Name: "GET Request Example", Name: "PostMan GET Method",
})
w.Header().Add("Content-Type", "application/json")
io.WriteString(w, string(marshal[:]))
break
case http.MethodPost:
var data map[string]interface{}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println(err)
} }
jsonResp, err := json.Marshal(resp) err = json.Unmarshal(body, &data)
if err != nil { if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "can not Unmarshal", http.StatusBadRequest)
return return
} }
w.Header().Set("Content-Type", "application/json") marshal, _ := json.Marshal(struct {
w.WriteHeader(http.StatusOK) Body map[string]interface{} `json:"Body"`
_, err = io.WriteString(w, string(jsonResp)) }{
Body: data,
})
w.Header().Add("Content-Type", "application/json")
io.WriteString(w, string(marshal[:]))
break
case http.MethodPut:
var data map[string]interface{}
body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
fmt.Println("Error writing response:", err) fmt.Println(err)
}
err = json.Unmarshal(body, &data)
if err != nil {
http.Error(w, "can not Unmarshal", http.StatusBadRequest)
return
} }
return
}
// ... 其他请求方法的处理 ... marshal, _ := json.Marshal(struct {
ID string `json:"ID"`
Name string `json:"Name"`
}{
ID: data["ID"].(string),
Name: "PostMan PUT Method",
})
w.Header().Add("Content-Type", "application/json")
io.WriteString(w, string(marshal[:]))
break
case http.MethodDelete:
if r.URL.Query().Get("ID") == "" {
http.Error(w,"ERROR : id is null",http.StatusBadRequest)
return
}
marshal, _ := json.Marshal(struct {
Name string `json:"Name"`
}{
Name: "PostMan DELETE Method",
})
w.Header().Add("Content-Type", "application/json")
io.WriteString(w, string(marshal[:]))
break
default:
log.Println("ERROR: Invalid HTTP Method")
w.WriteHeader(http.StatusBadRequest)
}
} }
func main() { func main() {

Loading…
Cancel
Save