1

Building an app with echo and basically created some routes. The GET ones are working fine, but the post one is give me the error: Do not really understand where the error lies here.

{...."method":"GET","uri":"/addPerson", message=Method Not Allowed","...."bytes_in":0,"bytes_out":33}

main.go snippet

    func initEchoServer() {
    e := echo.New()
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())
    // get all persons
    e.GET("/persons", Info)
    // get specific id
    e.GET("/persons/:id", getPerson)

    e.POST("/addPerson", addPerson)
    e.Logger.Fatal(e.Start(viper.GetString("port")))
}

func addPerson(c echo.Context) error {
    ctx := context.Background()
    db, err := sql.Open("postgres", "host=postgres port=5432 user=postgres dbname=postgres password=postgres sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }
    queries := postgres.New(db)
    insertedPerson, err := queries.CreatePersons(ctx, postgres.CreatePersonsParams{
        Firstname: "Mike",
        Lastname:  "Jordan",
    })
    if err != nil {
        log.Errorf("Failed to insert a person %v", err)
        return err
    }
    fmt.Println(insertedPerson)
    return c.JSONPretty(http.StatusOK, insertedPerson, "  ")
}

queries.sql.go snippet

type CreatePersonsParams struct {
    Firstname string
    Lastname  string
}

func (q *Queries) CreatePersons(ctx context.Context, arg CreatePersonsParams) (Person, error) {
    row := q.db.QueryRowContext(ctx, createPersons, arg.Firstname, arg.Lastname)
    var i Person
    err := row.Scan(&i.ID, &i.Firstname, &i.Lastname)
    return i, err
}
LogiBaer
  • 43
  • 3
  • When you register the handler with `e.POST` then presumably only `POST` requests will be routed to that handler. The error says you made the request with a `GET` method however: *'{...."method": **"GET",** "uri":"/addPerson", ...'* – mkopriva May 11 '22 at 15:49
  • I know this @Zombi Ive edited a snippet so you can see better – LogiBaer May 11 '22 at 15:54
  • @mkopriva yes I know that, but I do not understand where does it get GET from – LogiBaer May 11 '22 at 15:55
  • 3
    @LogiBaer it gets it from the client that made the request, no? – mkopriva May 11 '22 at 15:59

2 Answers2

1

If you register routes with POST in echo, it will only register POST method on that path. But it seems that you GET that path. You can use e.GET().

h3n4l
  • 36
  • 4
1

you're use post method in routers

e.POST("/addPerson", addPerson)

You can use postman to hit API using POST method, don't use browser

dwlpra
  • 76
  • 7