Created
April 18, 2019 09:30
-
-
Save ykyuen/2d06bd2c5b304cbdf59610e8725767f4 to your computer and use it in GitHub Desktop.
handling-http-request-in-go-echo-framework-2-01
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package api | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"github.com/labstack/echo" | |
"gitlab.com/ykyuen/handling-http-request-in-go-echo-example-1/model" | |
) | |
func PostFullName(c echo.Context) error { | |
// Bind the input data to ExampleRequest | |
exampleRequest := new(model.ExampleRequest) | |
if err := c.Bind(exampleRequest); err != nil { | |
return err | |
} | |
// Manipulate the input data | |
greeting := exampleRequest.FirstName + " " + exampleRequest.LastName | |
// Pretty print the json []byte | |
var resp bytes.Buffer | |
var b = []byte( | |
fmt.Sprintf(`{ | |
"first_name": %q, | |
"last_name": %q, | |
"msg": "Hello %s" | |
}`, exampleRequest.FirstName, exampleRequest.LastName, greeting), | |
) | |
err := json.Indent(&resp, b, "", " ") | |
if err != nil { | |
return err | |
} | |
// Return the json to the client | |
return c.JSONBlob( | |
http.StatusOK, | |
[]byte( | |
fmt.Sprintf("%s", resp.Bytes()), | |
), | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment