gin/golang - Empty Req Body - go

I'm new to Go and Gin, and am having trouble printing out the full request body.
I want to be able to read the request body from third party POST, but I'm getting empty request body
curl -u dumbuser:dumbuserpassword -H "Content-Type: application/json" -X POST --data '{"events": "3"}' http://localhost:8080/events
My entire code is as below. Any pointer is appreciated!
package main
import (
"net/http"
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
authorized := router.Group("/", gin.BasicAuth(gin.Accounts{
"dumbuser": "dumbuserpassword",
}))
authorized.POST("/events", events)
router.Run(":8080")
}
func events(c *gin.Context) {
fmt.Printf("%s", c.Request.Body)
c.JSON(http.StatusOK, c)
}

The problem here is that you're printing out the string value of c.Request.Body, which is of interface type ReadCloser.
What you can do to satisfy yourself that it does in fact contain the body you want is to read the value out of c.Request.Body to a string, and then print that out. This is for your learning process only!
Learning code:
func events(c *gin.Context) {
x, _ := ioutil.ReadAll(c.Request.Body)
fmt.Printf("%s", string(x))
c.JSON(http.StatusOK, c)
}
However, this is not the way you should access the body of the request. Let gin do the parsing of the body for you, by using a binding.
More correct code:
type E struct {
Events string
}
func events(c *gin.Context) {
data := &E{}
c.Bind(data)
fmt.Println(data)
c.JSON(http.StatusOK, c)
}
This is a more correct way to access the data in the body, since it will be already parsed out for you. Note that if you read the body first, as we did above in the learning step, the c.Request.Body will have been emptied, and so there will be nothing left in the body for Gin to read.
Broken code:
func events(c *gin.Context) {
x, _ := ioutil.ReadAll(c.Request.Body)
fmt.Printf("%s", string(x))
data := &E{}
c.Bind(data) // data is left unchanged because c.Request.Body has been used up.
fmt.Println(data)
c.JSON(http.StatusOK, c)
}
You're probably also curious why the JSON returned from this endpoint shows and empty Request.Body. This is for the same reason. The JSON Marshalling method cannot serialize a ReadCloser, and so it shows up as empty.

Related

How to log or print request received with gin?

Example:
func createOrUpdateInfluencer(c *gin.Context) { }
How to print the data in the request received in my function?
In my case, I am supposed to receive JSON, how to print it without knowing what it looks like?
Just read and print the body is ok:
func createOrUpdateInfluencer(c *gin.Context) {
body, _ := ioutil.ReadAll(c.Request.Body)
println(string(body))
}
Or if you just want to peek it in middleware, you can put it back after read:
func createOrUpdateInfluencer(c *gin.Context) {
body, _ := ioutil.ReadAll(c.Request.Body)
println(string(body))
c.Request.Body = ioutil.NopCloser(bytes.NewReader(body))
}
by using c.Request you can access to your reqeust object, then print/log everyting you must, like the headers:
fmt.Println(g.Request.Header)
fmt.Println(g.Request.Host)
// etc

How to correctly send RPC call using Golang to get smart-contract owner?

Update
Since I'm not able to achieve this using the approach in this question, I created my own library to do the same thing (link). It doesn't rely on go-ethereum package but use the normal net/http package to do JSON RPC request.
I still love to know what I did wrong in my approach below.
Definitions:
owner = public variable in contract with address type
contract = smart-contract that has owner
This is the curl request to get the owner of a contract. I managed to get the owner. (JSON RPC docs)
curl localhost:8545 -X POST \
--header 'Content-type: application/json' \
--data '{"jsonrpc":"2.0", "method":"eth_call", "params":[{"to": "0x_MY_CONTRACT_ADDRESS", "data": "0x8da5cb5b"}, "latest"], "id":1}'
{"jsonrpc":"2.0","id":1,"result":"0x000000000000000000000000_OWNER"}
But when I try to replicate it in Golang (code below), I got json: cannot unmarshal string into Go value of type main.response error. (go-ethereum code that I use)
package main
import (
"fmt"
"log"
"os"
"github.com/ethereum/go-ethereum/rpc"
)
func main() {
client, err := rpc.DialHTTP(os.Getenv("RPC_SERVER"))
if err != nil {
log.Fatal(err)
}
defer client.Close()
type request struct {
To string `json:"to"`
Data string `json:"data"`
}
type response struct {
Result string
}
req := request{"0x_MY_CONTRACT_ADDRESS", "0x8da5cb5b"}
var resp response
if err := client.Call(&resp, "eth_call", req, "latest"); err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", resp)
}
What did I miss here?
Expected result:
Address in string format. E.g. 0x3ab17372b25154400738C04B04f755321bB5a94b
P/S — I'm aware of abigen and I know it's better and easier to do this using abigen. But I'm trying to solve this specific issue without using abigen method.
You can solve the problem best using the go-ethereum/ethclient:
package main
import (
"context"
"log"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, _ := ethclient.Dial("https://mainnet.infura.io")
defer client.Close()
contractAddr := common.HexToAddress("0xCc13Fc627EFfd6E35D2D2706Ea3C4D7396c610ea")
callMsg := ethereum.CallMsg{
To: &contractAddr,
Data: common.FromHex("0x8da5cb5b"),
}
res, err := client.CallContract(context.Background(), callMsg, nil)
if err != nil {
log.Fatalf("Error calling contract: %v", err)
}
log.Printf("Owner: %s", common.BytesToAddress(res).Hex())
}
If you look at the client library code, you'll see that the JSON RPC response object is already disassembled and either an error is returned on failure, or the actual result parsed: https://github.com/ethereum/go-ethereum/blob/master/rpc/client.go#L277
The parser however already unwrapped the containing "result" field. Your type still wants to do an additional unwrap:
type response struct {
Result string
}
Drop the outer struct, simply pass a string pointer to the client.Call's first parameter.
Your response struct doesn't show the data that the json of the response has
try this
type response struct {
Jsonrpc string `json:"jsonrpc"`
ID int `json:"id"`
Result string `json:"result"`
}
json: cannot unmarshal string into Go value of type main.response error. I got similar type error when i was unmarshaling a response. It was because the response was actually json string, i mean it had Quotation " as first character. So to be sure you also encountered the same problem, please printf("%v",resp.Result) before unmarshaling in here https://github.com/ethereum/go-ethereum/blob/1ff152f3a43e4adf030ac61eb5d8da345554fc5a/rpc/client.go#L278.

Golang Type system inconsistency (http package)

I am trying to wrap my head around the GoLang type system, and there area a few things the confuse me.
So I have been working on the http library to try to understand this and I have come across the following that makes no sense.
package main
import (
"net/http"
"fmt"
"io/ioutil"
"io"
)
func convert(closer io.Closer) ([]byte) {
body, _ := ioutil.ReadAll(closer);
return body
}
func main() {
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://www.google.com", nil)
response, _ := client.Do(req);
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(body);
fmt.Println(convert(response.Body))
}
The Go Playground
this is not about the fact that the convert function is not needed it is the fact that the response body is of type io.closer and the ioutil.Readall takes a io.reader, yet I can pass it in, in one instance but not if in another. Is there something that I am missing that is magically happening.
I know that the closer technically passes the reader interface as it implements the the Read method but that should be true in both the function and the main body.
Any insight would be great.
Thanks
it is the fact that the response body is of type io.closer
No, it is not. Declaration of Request.Body is at http.Request:
Body io.ReadCloser
The Request.Body field is of type io.ReadCloser, it is both an io.Reader and an io.Closer.
Since it is an io.Reader (dynamic value of Request.Body implements io.Reader), you may use / pass it where an io.Reader is required, e.g. to ioutil.ReadAll().
Since it also implements io.Closer, you can also pass it where io.Closer is required, like your convert() function.
But inside convert the closer param has static type io.Closer, you can't use closer where an in.Reader is required. It might be (and in your case it is) that the dynamic type stored in closer also implements io.Reader, but there is no guarantee for this. Like in this example:
type mycloser int
func (mycloser) Close() error { return nil }
func main() {
var m io.Closer = mycloser(0)
convert(m)
}
In the above example closer inside convert() will hold a value of type mycloser, which truly does not implement io.Reader.
If your convert() function intends to treat its parameter also as an io.Reader, the parameter type should be io.ReadCloser:
func convert(rc io.ReadCloser) ([]byte, error) {
body, err := ioutil.ReadAll(rc)
if err != nil {
return body, err
}
err = rc.Close()
return body, err
}

How can I hard code a json string into an *http.Response for testing purposes in Go

I have some code that makes get requests to a dynamic website, which I want to test. Obviously the tests need to be run by anyone at any time, so rather than actually use the REST API, is it possible to put a json string into an *http.Response for testing purposes.
example code:
func get (c *http.Response, err error) (string, error) {
//code
}
test file:
func TestGet(t *testing.T) {
//code to have put json string for test *http.Response
get(???, nil)
}
You want to use a bytes.Buffer to turn the data you have into an io.Reader, and NopCloser (from io/ioutil) to make it an io.ReadCloser
r := &http.Response{
Status: "200 OK",
StatusCode: 200,
// etc., lots more fields needed here.
Body: ioutil.NopCloser(bytes.NewBufferString(json))
}
If you have your json in a []byte, then use NewBuffer instead of NewBufferString.

Sending json in POST request to web api written in web.go framework

Im using web.go (http://webgo.io/) for writing a simple web app that accepts json in a POST request and after parsing it returns the result. Im having trouble reading the json from ctx.Params object.
Below is the code i have so far
package main
import (
"github.com/hoisie/web";
"encoding/json"
)
func parse(ctx *web.Context, val string) string {
for k,v := range ctx.Params {
println(k, v)
}
//Testing json parsing
mapB := map[string]int{"apple": 5, "lettuce": 7}
mapD, _ := json.Marshal(mapB)
return string(mapD)
}
func main() {
web.Post("/(.*)", parse)
web.Run("0.0.0.0:9999")
}
Though the post request gets registered i dont see anything printed on the command line for the json i posted. How can i fix this ?
Thank You
The reason you're not getting any JSON data from the body of the POST request is because hoisie/web reads form data into .Params, as seen here:
req.ParseForm()
if len(req.Form) > 0 {
for k, v := range req.Form {
ctx.Params[k] = v[0]
}
}
In order to fix this, you'll need to add something that can parse the raw body of the response. You should just be able to use ctx.Body to access the raw body, since it implements *http.Request and doesn't redefine Body in the Context struct.
For example, this should work:
json := make(map[string]interface{})
body, err := ioutil.ReadAll(ctx.Body)
if err != nil {
// Handle Body read error
return
}
err = json.Unmarshal(body, &json)
if err != nil {
// Handle JSON parsing error
return
}
// Use `json`

Resources