dryvPacks

@dryv/go-net-http-backendv0.1.0

Standard-library Go net/http handlers with typed models and service boundaries.

Go net/http BackendBackendUnitPublished 7 days ago2 downloads

dryv pack add @dryv/go-net-http-backend
4.3 KBRaw ↗
jinja
// Code generated by Dryv. DO NOT EDIT.

package {{ pack.inputs.package_name }}

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"reflect"
	"strconv"
)

// HTTPError lets handwritten services choose an explicit HTTP failure response.
type HTTPError struct {
	Status  int
	Message string
	Payload any
}

func (e *HTTPError) Error() string {
	if e.Message != "" {
		return e.Message
	}
	return http.StatusText(e.Status)
}

func writeError(w http.ResponseWriter, err error) {
	var httpErr *HTTPError
	if errors.As(err, &httpErr) {
		if httpErr.Payload != nil {
			writeJSON(w, httpErr.Status, httpErr.Payload)
			return
		}
		http.Error(w, httpErr.Error(), httpErr.Status)
		return
	}
	http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}

func writeJSON(w http.ResponseWriter, status int, value any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if value == nil {
		return
	}
	if err := json.NewEncoder(w).Encode(value); err != nil {
		// Headers are already committed. There is no safe second response to write.
		return
	}
}

func decodeJSON(r *http.Request, output any) error {
	if r.Body == nil {
		return fmt.Errorf("request body is required")
	}
	defer r.Body.Close()
	if err := json.NewDecoder(r.Body).Decode(output); err != nil {
		return fmt.Errorf("invalid JSON body: %w", err)
	}
	return nil
}

func parseScalar(raw string, output any) error {
	rv := reflect.ValueOf(output)
	if rv.Kind() != reflect.Pointer || rv.IsNil() {
		return fmt.Errorf("parse target must be a non-nil pointer")
	}
	value := rv.Elem()

	switch value.Kind() {
	case reflect.String:
		value.SetString(raw)
		return nil
	case reflect.Bool:
		parsed, err := strconv.ParseBool(raw)
		if err != nil {
			return err
		}
		value.SetBool(parsed)
		return nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		parsed, err := strconv.ParseInt(raw, 10, value.Type().Bits())
		if err != nil {
			return err
		}
		value.SetInt(parsed)
		return nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		parsed, err := strconv.ParseUint(raw, 10, value.Type().Bits())
		if err != nil {
			return err
		}
		value.SetUint(parsed)
		return nil
	case reflect.Float32, reflect.Float64:
		parsed, err := strconv.ParseFloat(raw, value.Type().Bits())
		if err != nil {
			return err
		}
		value.SetFloat(parsed)
		return nil
	default:
		return json.Unmarshal([]byte(raw), output)
	}
}

func requiredQuery(r *http.Request, name string) (string, error) {
	values, ok := r.URL.Query()[name]
	if !ok || len(values) == 0 {
		return "", fmt.Errorf("missing required query parameter %q", name)
	}
	return values[0], nil
}

func optionalQuery(r *http.Request, name string) (string, bool) {
	values, ok := r.URL.Query()[name]
	if !ok || len(values) == 0 {
		return "", false
	}
	return values[0], true
}

func requiredHeader(r *http.Request, name string) (string, error) {
	values := r.Header.Values(name)
	if len(values) == 0 {
		return "", fmt.Errorf("missing required header %q", name)
	}
	return values[0], nil
}

func optionalHeader(r *http.Request, name string) (string, bool) {
	values := r.Header.Values(name)
	if len(values) == 0 {
		return "", false
	}
	return values[0], true
}

func requiredCookie(r *http.Request, name string) (string, error) {
	cookie, err := r.Cookie(name)
	if err != nil {
		return "", fmt.Errorf("missing required cookie %q", name)
	}
	return cookie.Value, nil
}

func optionalCookie(r *http.Request, name string) (string, bool) {
	cookie, err := r.Cookie(name)
	if err != nil {
		return "", false
	}
	return cookie.Value, true
}

func requiredForm(r *http.Request, name string) (string, error) {
	if err := r.ParseForm(); err != nil {
		return "", fmt.Errorf("invalid form body: %w", err)
	}
	values, ok := r.PostForm[name]
	if !ok || len(values) == 0 {
		return "", fmt.Errorf("missing required form field %q", name)
	}
	return values[0], nil
}

func optionalForm(r *http.Request, name string) (string, bool, error) {
	if err := r.ParseForm(); err != nil {
		return "", false, fmt.Errorf("invalid form body: %w", err)
	}
	values, ok := r.PostForm[name]
	if !ok || len(values) == 0 {
		return "", false, nil
	}
	return values[0], true, nil
}

func badRequest(w http.ResponseWriter, err error) {
	http.Error(w, err.Error(), http.StatusBadRequest)
}