databag/net/server/internal/httpUtil.go

66 lines
1.7 KiB
Go
Raw Normal View History

2022-01-17 21:27:48 +00:00
package databag
import (
2022-07-22 19:28:14 +00:00
"encoding/base64"
"encoding/json"
"errors"
"log"
"net/http"
"net/http/httptest"
"os"
"runtime"
"strings"
2022-01-17 21:27:48 +00:00
)
2022-07-23 05:47:09 +00:00
//WriteResponse serialze and write json body for response
2022-01-17 21:27:48 +00:00
func WriteResponse(w http.ResponseWriter, v interface{}) {
2022-07-22 19:28:14 +00:00
body, err := json.Marshal(v)
if err != nil {
_, file, line, _ := runtime.Caller(1)
p, _ := os.Getwd()
log.Printf("%s:%d %s", strings.TrimPrefix(file, p), line, err.Error())
w.WriteHeader(http.StatusInternalServerError)
} else {
w.Header().Set("Content-Type", "application/json")
w.Write(body)
}
2022-01-17 21:27:48 +00:00
}
2022-07-23 05:47:09 +00:00
//ReadResponse read and parse json response body
2022-01-17 21:27:48 +00:00
func ReadResponse(w *httptest.ResponseRecorder, v interface{}) error {
2022-07-22 19:28:14 +00:00
resp := w.Result()
if resp.StatusCode != 200 {
return errors.New("response failed")
}
if v == nil {
return nil
}
dec := json.NewDecoder(resp.Body)
dec.Decode(v)
return nil
2022-01-17 21:27:48 +00:00
}
2022-07-23 05:47:09 +00:00
//SetBasicAuth sets basic auth in authorization header
2022-01-17 21:27:48 +00:00
func SetBasicAuth(r *http.Request, login string) {
2022-07-22 19:28:14 +00:00
auth := base64.StdEncoding.EncodeToString([]byte(login))
r.Header.Add("Authorization", "Basic "+auth)
2022-01-17 21:27:48 +00:00
}
2022-07-23 05:47:09 +00:00
//SetBearerAuth sets bearer auth token in header
2022-01-17 21:27:48 +00:00
func SetBearerAuth(r *http.Request, token string) {
2022-07-22 19:28:14 +00:00
r.Header.Add("Authorization", "Bearer "+token)
2022-01-17 21:27:48 +00:00
}
2022-07-23 05:47:09 +00:00
//SetCredentials set basic auth in credentials header
2022-01-17 21:27:48 +00:00
func SetCredentials(r *http.Request, login string) {
2022-07-22 19:28:14 +00:00
auth := base64.StdEncoding.EncodeToString([]byte(login))
r.Header.Add("Credentials", "Basic "+auth)
2022-01-17 21:27:48 +00:00
}
2022-07-23 05:47:09 +00:00
//ParseRequest read and parse json request body
2022-01-17 21:42:17 +00:00
func ParseRequest(r *http.Request, w http.ResponseWriter, obj interface{}) error {
2022-07-22 19:28:14 +00:00
r.Body = http.MaxBytesReader(w, r.Body, APPBodyLimit)
dec := json.NewDecoder(r.Body)
return dec.Decode(&obj)
2022-01-17 21:42:17 +00:00
}