コード例 #1
0
ファイル: respond.go プロジェクト: skanct/argo-web-api
// Respond will be called to answer to http requests to the PI
func (confhandler *ConfHandler) Respond(fn func(r *http.Request, cfg config.Config) (int, http.Header, []byte, error)) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		defer func() {
			if r := recover(); r != nil {
				logging.HandleError(r)
			}
		}()

		code, header, output, err := fn(r, confhandler.Config)

		if code == http.StatusInternalServerError {
			log.Panic("Internal Server Error:", fmt.Sprintf("%+v", err))
		}

		//Add headers
		header.Set("Content-Length", fmt.Sprintf("%d", len(output)))

		for name, values := range header {
			for _, value := range values {
				w.Header().Add(name, value)
			}
		}

		w.WriteHeader(code)
		w.Write(output)
	})

}
コード例 #2
0
// Respond will be called to answer to http requests to the PI
func (confhandler *ConfHandler) Respond(fn func(r *http.Request, cfg config.Config) (int, http.Header, []byte, error)) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		defer func() {
			if r := recover(); r != nil {
				logging.HandleError(r)
			}
		}()

		code, header, output, err := fn(r, confhandler.Config)

		if code == http.StatusInternalServerError {
			log.Panic("Internal Server Error:", fmt.Sprintf("%+v", err))
		}

		//Add headers
		header.Set("Content-Length", fmt.Sprintf("%d", len(output)))

		if confhandler.Config.Server.EnableCors {
			header.Set("Access-Control-Allow-Origin", "*")
			header.Set("Access-Control-Allow-Headers", "Content-Type, Accept, x-api-key")
			header.Set("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
		}

		for name, values := range header {
			for _, value := range values {
				w.Header().Add(name, value)
			}
		}

		w.WriteHeader(code)
		w.Write(output)
	})

}