• Type:

CH Show HN: Parsrus – Parse JSON and XML for Golang Web APIs

Parsrus

Return json or xml for golang web apis.

Usage

To install Parsrus

    go get github.com/mattb2401/parsrus

To add Parsrus in your code

    import (
        "net/http"
        "github.com/mattb2401/parsrus"
    )

    // Return json request
    func JSONRequestHandler(w http.ResponseWriter, r *http.Request){
        // parsrus.Parser struct fields {ResponseWriter, ContentType}
        p := parsrus.Parser{ResponseWriter: w, ContentType: "json"}
        // p.Parse() takes a map[string]interface{} 
        p.Parse(parsrus.Fields{"code": "200", "message": "json parsed"})
        return
    }

    // Return xml request. Add RootTag for root element in your xml when initializing parsrus struct. 
    func XMLRequestHandler(w http.ResponseWriter, r *http.Request){
         // parsrus.Parser struct fields {ResponseWriter, ContentType, RootTag}
        p := parsrus.Parser{ResponseWriter: w, ContentType: "xml", RootTag: "request"}
         // parsrus.Parser struct fields {ResponseWriter, ContentType}
        p.Parse(parsrus.Fields{"code": "200", "message": "xml parsed"})
        return
    }
    // Return json request with specified http code
    func JSONRequestHandlerWithStatusCode(w http.ResponseWriter, r *http.Request) {
        // parsrus.Parser struct fields {ResponseWriter, ContentType}
        p := parsrus.Parser{ResponseWriter: w, ContentType: "json"}
        // p.Parse() takes a map[string]interface{} of parsrus.Fields and http code
        p.Parse(parsrus.Fields{"code": "200", "message": "json parsed"}, 200)
        return
    }

    //You can serialize an interface to JSON or XML using the Serialize functon
    func JSONRequestHandlerWithStatusCode(w http.ResponseWriter, r *http.Request) {
        // parsrus.Parser struct fields {ResponseWriter, ContentType}
        p := parsrus.Parser{ResponseWriter: w, ContentType: "json"}
        // p.Serialize() takes any map[string]interface{} and http code
        p.Serialize(map[string]interface{}{"data": "boom"}, 200)
        return
    }

Read More

Previous Post

CH Show HN: Larq – Binarized Neural Network Inference with MLIR and TFLite

Next Post

CH Show HN: Cloud Native Tunnel Written in Go

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top