| 1 |
package http |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/json" |
| 6 |
"fmt" |
| 7 |
"net/http" |
| 8 |
"reflect" |
| 9 |
) |
| 10 |
|
| 11 |
func MarshalJSON(w http.ResponseWriter, i any) { |
| 12 |
MarshalJSONWithStatus(w, i, http.StatusOK) |
| 13 |
} |
| 14 |
|
| 15 |
func MarshalJSONWithStatus(w http.ResponseWriter, i any, status int) { |
| 16 |
w.Header().Set("content-type", "application/json") |
| 17 |
w.WriteHeader(status) |
| 18 |
if i == nil || (reflect.ValueOf(i).Kind() == reflect.Ptr && reflect.ValueOf(i).IsNil()) { |
| 19 |
return |
| 20 |
} |
| 21 |
err := json.NewEncoder(w).Encode(i) |
| 22 |
if err != nil { |
| 23 |
http.Error(w, err.Error(), http.StatusInternalServerError) |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
func ConcatenateJSON(first, second []byte) ([]byte, error) { |
| 28 |
if !bytes.HasSuffix(first, []byte{'}'}) { |
| 29 |
return nil, fmt.Errorf("jws: invalid JSON %s", first) |
| 30 |
} |
| 31 |
if !bytes.HasPrefix(second, []byte{'{'}) { |
| 32 |
return nil, fmt.Errorf("jws: invalid JSON %s", second) |
| 33 |
} |
| 34 |
// check empty |
| 35 |
if len(first) == 2 { |
| 36 |
return second, nil |
| 37 |
} |
| 38 |
if len(second) == 2 { |
| 39 |
return first, nil |
| 40 |
} |
| 41 |
|
| 42 |
first[len(first)-1] = ',' |
| 43 |
first = append(first, second[1:]...) |
| 44 |
return first, nil |
| 45 |
} |