调用API时找不到服务或方法时也提示JSON,防止小白开发者不知道如何获取响应状态

This commit is contained in:
刘祥超
2024-01-12 11:51:06 +08:00
parent a3c0b43bc4
commit 7f20ad32b6

View File

@@ -67,6 +67,11 @@ func (this *RestServer) handle(writer http.ResponseWriter, req *http.Request) {
var matches = servicePathReg.FindStringSubmatch(path) var matches = servicePathReg.FindStringSubmatch(path)
if len(matches) != 3 { if len(matches) != 3 {
writer.WriteHeader(http.StatusNotFound) writer.WriteHeader(http.StatusNotFound)
this.writeJSON(writer, maps.Map{
"code": "404",
"message": "invalid api path '" + path + "'",
"data": maps.Map{},
}, shouldPretty)
return return
} }
@@ -76,11 +81,21 @@ func (this *RestServer) handle(writer http.ResponseWriter, req *http.Request) {
serviceType, ok := restServicesMap[serviceName] serviceType, ok := restServicesMap[serviceName]
if !ok { if !ok {
writer.WriteHeader(http.StatusNotFound) writer.WriteHeader(http.StatusNotFound)
this.writeJSON(writer, maps.Map{
"code": "404",
"message": "service '" + serviceName + "' not found",
"data": maps.Map{},
}, shouldPretty)
return return
} }
if len(methodName) == 0 { if len(methodName) == 0 {
writer.WriteHeader(http.StatusNotFound) writer.WriteHeader(http.StatusNotFound)
this.writeJSON(writer, maps.Map{
"code": "404",
"message": "method '" + methodName + "' not found",
"data": maps.Map{},
}, shouldPretty)
return return
} }
@@ -94,19 +109,39 @@ func (this *RestServer) handle(writer http.ResponseWriter, req *http.Request) {
method = serviceType.MethodByName(methodName) method = serviceType.MethodByName(methodName)
if !method.IsValid() { if !method.IsValid() {
writer.WriteHeader(http.StatusNotFound) writer.WriteHeader(http.StatusNotFound)
this.writeJSON(writer, maps.Map{
"code": "404",
"message": "method '" + methodName + "' not found",
"data": maps.Map{},
}, shouldPretty)
return return
} }
} else { } else {
writer.WriteHeader(http.StatusNotFound) writer.WriteHeader(http.StatusNotFound)
this.writeJSON(writer, maps.Map{
"code": "404",
"message": "method '" + methodName + "' not found",
"data": maps.Map{},
}, shouldPretty)
return return
} }
} }
if method.Type().NumIn() != 2 || method.Type().NumOut() != 2 { if method.Type().NumIn() != 2 || method.Type().NumOut() != 2 {
writer.WriteHeader(http.StatusNotFound) writer.WriteHeader(http.StatusNotFound)
this.writeJSON(writer, maps.Map{
"code": "404",
"message": "method '" + methodName + "' not found",
"data": maps.Map{},
}, shouldPretty)
return return
} }
if method.Type().In(0).Name() != "Context" { if method.Type().In(0).Name() != "Context" {
writer.WriteHeader(http.StatusNotFound) writer.WriteHeader(http.StatusNotFound)
this.writeJSON(writer, maps.Map{
"code": "404",
"message": "method '" + methodName + "' not found (or invalid context)",
"data": maps.Map{},
}, shouldPretty)
return return
} }