feat: add json response

master
Evan Chen 2021-11-12 09:52:26 +08:00
parent 0f740a700a
commit 6fde850d35
1 changed files with 10 additions and 0 deletions

10
net.go
View File

@ -1,6 +1,7 @@
package ksrv package ksrv
import ( import (
"encoding/json"
"net/http" "net/http"
"strconv" "strconv"
) )
@ -35,6 +36,15 @@ func Response(w http.ResponseWriter, status int, body []byte) (int, error) {
return w.Write(body) return w.Write(body)
} }
func JSON(w http.ResponseWriter, value interface{}) {
data, err := json.Marshal(value)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
// Abort shorthand for aborting with error, strings and status code could also be passed // Abort shorthand for aborting with error, strings and status code could also be passed
func Abort(w http.ResponseWriter, errs ...interface{}) (int, error) { func Abort(w http.ResponseWriter, errs ...interface{}) (int, error) {
code := 500 code := 500