I am new to Go language, and currently I try to create a api server by using “net/http” package. At the moment, I found an issue that I create lots of json Decoser object when the “test” API called. Like this code snippet shows:
func handleRequest(w http.ResponseWriter, r *http.Request) {
fmt.Println("handleRequest")
if strings.Contains(r.URL.Path, "/delete/") {
handleDelete(w, r)
return
}
response := make(chan string)
switch r.Method {
case "GET":
func(w http.ResponseWriter, r *http.Request) {
messageChan <- message{command: "get", response: response}
responseData := <-response
fmt.Fprintln(w, responseData)
}(w, r)
case "POST":
func(w http.ResponseWriter, r *http.Request) {
people := requestDecoder(w, r)
messageChan <- message{command: "put", key: people.Name, value: people.Age, response: response}
fmt.Fprintln(w, <-response)
}(w, r)
case "PUT":
func(w http.ResponseWriter, r *http.Request) {
people := requestDecoder(w, r)
messageChan <- message{command: "put", key: people.Name, value: people.Age, response: response}
if <-response == "not found" {
http.Error(w, "not found", http.StatusNotFound)
}
fmt.Fprintln(w, <-response)
}(w, r)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
func NewServer() {
peopleMap["yan"] = 18
peopleMap["li"] = 19
go run()
server := &http.Server{Addr: ":8080"}
http.HandleFunc("/test", handleRequest)
http.HandleFunc("/delete/", handleDelete)
terminate := make(chan os.Signal, 1)
go func() {
err := server.ListenAndServe()
if err != nil {
log.Fatal("server error: ", err)
}
}()
go func() {
<-terminate
err := server.Close()
if err != nil {
log.Fatal("server error: ", err)
}
}()
<-terminate
}
func requestDecoder(w http.ResponseWriter, r *http.Request) People {
decoder := json.NewDecoder(r.Body)
var people People
err := decoder.Decode(&people)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
return people
}
I am wondering if there are any way to avoid creating pretty much object as it will impact GC
Avoid createing too many small object.
New contributor
jun yan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.