Skip to content

apihandler package provides a simple 'http.Handler' implementation with a REST friendly API syntax. Provides simple methods to assign handlers to a path by HTTP method.

License

Notifications You must be signed in to change notification settings

lucasmenendez/apihandler

Repository files navigation

Last release GoDoc Go Report Card test license

APIHandler

apihandler package provides a simple http.Handler implementation with a REST friendly API syntax. Provides simple methods to assign handlers to a path by HTTP method.

Installation

go get github.com/lucasmenendez/apihandler

Basic example

Check out the full example here.

// create and register a new GET handler
handler := NewHandler()
err := handler.Get("/service/{service_name}/resource/{resource_name}",
    func(w http.ResponseWriter, r *http.Request) {
        // get router arguments from Header
        status := map[string]string{
            "service":  apihandler.URIParam(r.Context(), "service_name"),
            "resource": apihandler.URIParam(r.Context(), "resource_name"),
            "status":   "ok",
        }
        // encoding response
        body, err := json.Marshal(status)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            _, _ = w.Write([]byte(fmt.Sprintf("error encoding status: %s", err)))
            return
        }
        // writing response
        _, _ = w.Write(body)
    })
if err != nil {
    log.Printf("ERR: error listening for requests: %s\n", err)
}
// run http server with created handler
if err := http.ListenAndServe(":8090", handler); err != nil {
    log.Printf("ERR: error listening for requests: %s\n", err)
    return
}

About

apihandler package provides a simple 'http.Handler' implementation with a REST friendly API syntax. Provides simple methods to assign handlers to a path by HTTP method.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages