-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiHandler.go
40 lines (34 loc) · 1.18 KB
/
apiHandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package handler
import (
"fmt"
"net/http"
"github.com/fengjian0106/gomgo/appcontext"
"github.com/fengjian0106/gomgo/database"
)
type ApiHandler struct {
AppCtx *appcontext.AppContext
Handler func(*appcontext.AppContext, http.ResponseWriter, *http.Request) (int, error)
}
//if you want server-end rendering view, maybe you can use ViewHandler
func (ah ApiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
status, err := ah.Handler(ah.AppCtx, w, r)
if err != nil {
//log.Printf("HTTP %d: %v", status, err)
var errJson string
switch err.(type) {
case *ApiError:
apiErr, _ := err.(*ApiError)
errJson = fmt.Sprintf("{\"code\": %d, \"err\": \"%s\"}", apiErr.Code, apiErr.Err.Error())
case *database.DbError:
dbErr, _ := err.(*database.DbError)
errJson = fmt.Sprintf("{\"code\": %d, \"err\": \"%s\"}", dbErr.Code, dbErr.Err.Error())
default:
apiErr := ApiError{ApiErrorUnknow, err}
errJson = fmt.Sprintf("{\"code\": %d, \"err\": \"%s\"}", apiErr.Code, apiErr.Err.Error())
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write([]byte(errJson))
//http.Error(w, errJson, status) //this func just return plane textmimetype
}
}