http

package
v2.36.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2022 License: MIT Imports: 13 Imported by: 0

README

Package http

This package contains http handler related to help you write handler easier and have a standardized response.

How to create custom handler

To create custom handler using this package, you need to declare the handler using this function signature:

func(w http.ResponseWriter, r *http.Request) (data interface{}, pageToken *string, err error)

This handler requires you to return the response data, page token and error if any. response data is the struct for the response data page token is the optional hashed or encoded page token for pagination. We enforce this approach for pagination since it's the most clean way to do a pagination.' This approach support infinite scroll and traditional pagination. error is the error (if any)

Example:

func HelloHandler(w http.ResponseWriter, r *http.Request) (data interface{}, pageToken *string, err error) {
    // Data we will return
	data = Person{
		FirstName: "Budi",
		LastName:  "Ariyanto",
	}

    // The token
	token := "o934ywjkhk67j78sd9af=="
    pageToken = &token
    
    // error, should be something like this
    // if err != nil {
    //    return err
    //}

	return
}

func main() {
    // Meta is metadata for the response
	meta := structs.Meta{
		Version: "v1.2.3",
		Status:  "stable",
		APIEnv:  "prod-test",
	}

	// When new context handler is created, it will inject all general error map.
	// Then you should add your necessary own error to the handler.
	handlerCtx := phttp.NewContextHandler(meta)

	// add error individualy
	var ErrCustom *structs.ErrorResponse = &structs.ErrorResponse{
		Response: structs.Response{
			ResponseCode: "00011",
			ResponseDesc: structs.ResponseDesc{
				ID: "Custom error",
				EN: "Custom error",
			},
		},
		HttpStatus: http.StatusInternalServerError,
	}
	handlerCtx.AddError(errors.New("custom error"), ErrCustom)

	// add error individualy
	var ErrCustom2 *structs.ErrorResponse = &structs.ErrorResponse{
		Response: structs.Response{
			ResponseCode: "00011",
			ResponseDesc: structs.ResponseDesc{
				ID: "Custom error",
				EN: "Custom error",
			},
		},
		HttpStatus: http.StatusInternalServerError,
	}

	// add error individualy
	var ErrCustom3 *structs.ErrorResponse = &structs.ErrorResponse{
		Response: structs.Response{
			ResponseCode: "00011",
			ResponseDesc: structs.ResponseDesc{
				ID: "Custom error",
				EN: "Custom error",
			},
		},
		HttpStatus: http.StatusInternalServerError,
	}

	// add error by setup error map at first
	customError2 := errors.New("Custom error 2")
	customError3 := errors.New("Custom error 3")
	errMap := map[error]*structs.ErrorResponse{
		customError2: ErrCustom2,
		customError3: ErrCustom3,
	}

	// add error map
	handlerCtx.AddErrorMap(errMap)

    // newHandler is a function that will create function for create new custom handler with injected handler context
    newHandler := phttp.NewHttpHandler(handlerCtx)
    
    // helloHandler is the handler
	helloHandler := newHandler(HelloHandler)

	router := chi.NewRouter()
	router.Get("/hello", helloHandler.ServeHTTP)

	http.ListenAndServe(":5678", router)
}

From the example above, you can see you only care about the data, pageToken and error, then this custom handler will construct the response itself. This response are refer to Kitabisa API response standardization.

How to use http metrics

This http metrics will send your http metrics (response time, error status, and success status) to telegraf.

Usage:

handlerCtx := phttp.NewContextHandler(pstructs.Meta{
	Version: "v1.2.3",
	Status:  "stable",
	APIEnv:  "prod-test",
})

telegrafHost := "telegraf.localhost"
telegrafPort := 8125
serviceName := "my-service" // serviceName identifies your service in the telegraf storage (e.g., Influxdb, etc)

phandler := phttp.NewHttpHandler(
	handlerCtx,
	phttp.WithMetric(telegrafHost, telegrafPort, serviceName),
)

Disable HTML Escaping In Http Response

You can optionally disable HTML escaping to your response, by set Disable-Html-Escape=true in your response header. The default is Disable-Html-Escape=false.

Example: Add:

w.Header().Set("Disable-Html-Escape", "true")

To your handler that need escaping to be disabled.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreatePageToken added in v2.15.3

func CreatePageToken(arrayData interface{}, dataLimit int, fieldNameId string, fieldNameDate string) (nextToken string)

func LookupError

func LookupError(lookup map[error]*structs.ErrorResponse, err error) (res *structs.ErrorResponse)

LookupError will get error message based on error type, with variables if you want give dynamic message error

func NewHttpHandler

func NewHttpHandler(c HttpHandlerContext, opts ...HandlerOption) func(handler func(w http.ResponseWriter, r *http.Request) (interface{}, *string, error)) HttpHandler

func ParsePageToken added in v2.15.3

func ParsePageToken(pageToken string) (token map[string]string)

func PathPattern added in v2.20.0

func PathPattern(input string) string

PathPattern modify params on url

Types

type CustomWriter

type CustomWriter struct {
	C HttpHandlerContext
}

func (*CustomWriter) Write

func (c *CustomWriter) Write(w http.ResponseWriter, data interface{}, nextPage *string)

func (*CustomWriter) WriteError

func (c *CustomWriter) WriteError(w http.ResponseWriter, err error)

WriteError sending error response based on err type

type HandlerOption added in v2.17.0

type HandlerOption func(*HttpHandler)

func WithMetric added in v2.17.0

func WithMetric(telegrafHost string, telegrafPort int, svcName string) HandlerOption

WithMetric wire statsd client to perkakas handler

type HttpHandler

type HttpHandler struct {
	// H is handler, with return interface{} as data object, *string for token next page, error for error type
	H func(w http.ResponseWriter, r *http.Request) (interface{}, *string, error)
	CustomWriter
	Metric      *statsd.Client
	ServiceName string
}

func (HttpHandler) ServeHTTP

func (h HttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type HttpHandlerContext

type HttpHandlerContext struct {
	M structs.Meta
	E map[error]*structs.ErrorResponse
}

func NewContextHandler added in v2.7.0

func NewContextHandler(meta structs.Meta) HttpHandlerContext

func (HttpHandlerContext) AddError added in v2.7.0

func (hctx HttpHandlerContext) AddError(key error, value *structs.ErrorResponse)

func (HttpHandlerContext) AddErrorMap added in v2.7.0

func (hctx HttpHandlerContext) AddErrorMap(errMap map[error]*structs.ErrorResponse)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL