Generic api functions
Find a file
2022-01-31 13:12:51 +03:00
_examples Added custom renderers 2022-01-09 08:03:03 +03:00
contracts.go Added custom renderers 2022-01-09 08:03:03 +03:00
go.mod Update go.mod 2022-01-31 13:11:54 +03:00
LICENSE Initial commit 2021-12-19 20:05:02 +03:00
README.md Update README.md 2022-01-31 13:12:51 +03:00
wrap.go Added custom renderers 2022-01-09 08:03:03 +03:00

API wrapper

API handler wrapper

Usage

api.Wrap(handler)

Function Wrap wraps API handler and returns standard http.HandlerFunc. It encapsulate body parsing.

Example

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"github.com/neonxp/api"
)

func main() {
	h := &http.Server{Addr: "0.0.0.0:3000"}
	mux := http.NewServeMux()
	h.Handler = mux

	// Here is magic!
	mux.Handle("/hello", api.Wrap(handleHello))

	if err := h.ListenAndServe(); err != http.ErrServerClosed {
		log.Fatalln(err)
	}
}

// Our API handler with custom request and response types
func handleHello(ctx context.Context, req *helloRequest) (*helloResponse, error) {
	return &helloResponse{Message: fmt.Sprintf("Hello, %s!", req.Name)}, nil
}

// Custom request type
type helloRequest struct {
	Name string `json:"name"`
}

// Custom response type
type helloResponse struct {
	Message string `json:"message"`
}