Files

42 lines
824 B
Go

package web
import (
"context"
"encoding/json"
"log"
"net/http"
"strconv"
)
// Server will respond with an expected struct of information.
// Otherwise will return the correct error status code.
// Client responsibility to check status then unmarshal to
// error response or data
func WriteJSON[T any](w http.ResponseWriter, status int, data T) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(data); err != nil {
log.Printf("JSON encode error %v", err)
}
}
func userIDFromContext(ctx context.Context) (int64, bool) {
val := ctx.Value(userIDKey)
if val == nil {
return 0, false
}
strID, ok := val.(string)
if !ok {
return 0, false
}
id, err := strconv.ParseInt(strID, 10, 64)
if err != nil {
return 0, false
}
return id, true
}