jjeffery / httpapi

Package for servers that implement a JSON Web API.

Home Page:https://godoc.org/github.com/jjeffery/httpapi

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

httpapi GoDoc License Build Status Coverage Status GoReportCard

Package httpapi provides support for implementing HTTP servers that expose a JSON API.

Example of a handler that extracts the input from the body of the HTTP request.

func postHandler(w http.ResponseWriter, r *http.Request) {
    // unmarshal input from request
    var input DoSomethingInput
    if err := httpapi.ReadRequest(w, r, &input); err != nil {
        httpapi.WriteError(w, r, err)
        return
    }

    output, err := doSomethingWith(r.Context(), &input)
    if err != nil {
        httpapi.WriteError(w, r, err)
        return
    }

    httpapi.WriteResponse(w, r, output)
}

Example of a handler that extracts the input from the query strings of the HTTP request.

func getHandler(w http.ResponseWriter, r *http.Request) {
    query := httpapi.Query(r)
    input := DoAnotherThingInput {
        Since: query.GetTime("since"),
        Limit: query.GetInt("limit"),
        Offset: query.GetInt("offset"),
    }

    // validate once after all query string parameters have been read
    if err := query.Err(); err != nil {
        httpapi.WriteResponse(w, r, err)
        return
    }

    output, err := doAnotherThingWith(r.Context(), &input)
    if err != nil {
        httpapi.WriteError(w, r, err)
        return
    }

    httpapi.WriteResponse(w, r, output)
}

Read the package documentation for more information.

About

Package for servers that implement a JSON Web API.

https://godoc.org/github.com/jjeffery/httpapi

License:MIT License


Languages

Language:Go 100.0%