You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
p6b5nefl7 789f73cc04
Update README.md
9 months ago
README.md Update README.md 9 months ago

README.md

package main

import (
"encoding/json"
"fmt"
"io"
"net/http"
)

func getRequest(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet:

	if r.URL.Query().Get("ID") == "" {
		http.Error(w,"ERROR : id is null",http.StatusBadRequest)
		return
	}
    
	marshal, _ := json.Marshal(struct {
		ID string `json:"ID"`
		Name string `json:"Name"`
	}{
		ID: r.URL.Query().Get("ID"),
		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)
	}

	err = json.Unmarshal(body, &data)
	if err != nil {
		http.Error(w, "can not Unmarshal", http.StatusBadRequest)
		return
	}
    
	marshal, _ := json.Marshal(struct {
		Body map[string]interface{} `json:"Body"`
	}{
		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 {
		fmt.Println(err)
	}

	err = json.Unmarshal(body, &data)
	if err != nil {
		http.Error(w, "can not Unmarshal", http.StatusBadRequest)
		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() {
// 将你的请求处理程序绑定到/test路径
http.HandleFunc("/test", getRequest)

// 监听1024端口注意可能需要root权限或使用高于1024的端口  
fmt.Println("Starting server on port 1024...")  
if err := http.ListenAndServe(":1024", nil); err != nil {  
	fmt.Println("Error starting server:", err)  
}  

}