What's the way to abort my API serving with some error message?
Link to call my service:
http://creative.test.spoti.io/api/getVastPlayer?add=
{"Json":Json}&host=api0.spoti.io&domain=domain&userAgent=userAgent&mobile=true
To call my service the client need to send a Json and some params.
I want to test if the params that I get are correct, if not I want send a error message.
The response should be a Json Code {"Result":"Result","Error":"error message"}
I tried log.fatal
and os.Exit(1)
they stop the service, not just the call request. panic
aborts the call but it prevents me to send a http.ResponseWriter
which is my error message.
I read something about panic, defer, recover but I don't really know how can I use them to solve this problem.
return
works:
mobile :=query.Get("mobile")
if mobile=="mobile" {
str:=`{"Resultt":"","Error":"No valide Var"}`
fmt.Fprint(w, str)
fmt.Println("No successfull Operation!!")
return}
But I can use it just in the main function, because in the other functions it exits just the func not the caller function (request).
Terminating the serving of an HTTP request is nothing more than to return from the
ServeHTTP()
method, e.g.:Notes:
If the input params of your API service are invalid, you should consider returning an HTTP error code instead of the implied default
200 OK
. For this you can use thehttp.Error()
function, for example:For a more sophisticated example where you send back JSON data along with the error code:
Example showing how to propagate "returning"
If the error is detected outside of
ServeHTTP()
, e.g. in a function that is called fromServeHTTP()
, you have to return this error state so thatServeHTTP()
can return.Let's assume you have the following custom type for your required parameters and a function which is responsible to decode them from a request:
Using these:
Also see this related question: Golang, how to return in func FROM another func?