go - Golang: terminating or aborting an HTTP request -
what's way abort api serving error message?
link call service:
http://creative.test.spoti.io/api/getvastplayer?add= {"json":json}&host=api0.spoti.io&domain=domain&useragent=useragent&mobile=true to call service client need send json , params.
i want test if params correct, if not want send error message.
the response should json code {"result":"result","error":"error message"}
i tried log.fatal , os.exit(1) stop service, not call request. panic aborts call prevents me send http.responsewriter error message.
i read panic, defer, recover don't know how can use them solve 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 can use in main function, because in other functions exits func not caller function (request).
terminating serving of http request nothing more return servehttp() method, e.g.:
http.handlefunc("/", func(w http.responsewriter, r *http.request) { // examine incoming params if !ok { str := `{"result":"","error":"no valide var"}` fmt.fprint(w, str) return } // normal api serving }) panic(http.listenandserve(":8080", nil)) notes:
if input params of api service invalid, should consider returning http error code instead of implied default 200 ok. can use http.error() function, example:
http.handlefunc("/", func(w http.responsewriter, r *http.request) { // examine incoming params if !ok { http.error(w, `invalid input params!`, http.statusbadrequest) return } // normal api serving }) for more sophisticated example send json data along error code:
http.handlefunc("/", func(w http.responsewriter, r *http.request) { // examine incoming params if !ok { w.header().set("content-type", "application/json") w.writeheader(http.statusbadrequest) str := `{"result":"","error":"no valide var"}` fmt.fprint(w, str) return } // normal api serving }) example showing how propagate "returning"
if error detected outside of servehttp(), e.g. in function called servehttp(), have return error state servehttp() can return.
let's assume have following custom type required parameters , function responsible decode them request:
type params struct { // fields params } func decodeparams(r *http.request) (*params, error) { p := new(params) // decode params, if invalid, return error: if !ok { return nil, errors.new("invalid params") } // if goes well: return p, nil } using these:
http.handlefunc("/", func(w http.responsewriter, r *http.request) { p, err := decodeparams(r) if err != nil { http.error(w, `invalid input params!`, http.statusbadrequest) return } // normal api serving }) also see related question: golang, how return in func func?
Comments
Post a Comment