-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to parse string to mail.Address #2743
Comments
Could you provide how |
The type type Address struct {
Name string
Address string
} Echo version |
This package main
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"log/slog"
"net/http"
"net/mail"
)
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.POST("/", func(c echo.Context) error {
type NewEmail struct {
From mail.Address `form:"from"`
}
dto := &NewEmail{}
if err := c.Bind(dto); err != nil { // dto is *NewEmail
return c.JSON(http.StatusBadRequest, map[string]interface{}{"error": err.Error()})
}
return c.JSON(http.StatusOK, dto)
})
if err := e.Start(":8080"); err != nil {
slog.Error("failed to start server")
}
} does not work because you can only bind forms to (struct) fields that are explicitly marked with struct tags. But currently the target is struct with additional fields - this is not supported. You could create your own address type and add tags e.POST("/", func(c echo.Context) error {
type Address struct {
Name string `form:"name"`
Address string `form:"address"`
}
type NewEmail struct {
From Address
}
dto := &NewEmail{}
if err := c.Bind(dto); err != nil { // dto is *NewEmail
return c.JSON(http.StatusBadRequest, map[string]interface{}{"error": err.Error()})
}
return c.JSON(http.StatusOK, dto)
}) test with curl --form name=testName --form address=testAddress http://localhost:8080/ |
note: e.POST("/", func(c echo.Context) error {
type NewEmail struct {
From mail.Address
}
dto := &NewEmail{}
if err := c.Bind(dto); err != nil { // dto is *NewEmail
return c.JSON(http.StatusBadRequest, map[string]interface{}{"error": err.Error()})
}
return c.JSON(http.StatusOK, dto)
}) but this is because standard library JSON unmarshalling supports this |
I am trying to parse the following
with
Getting following error
unknown type
I've checked that it works if I make
NewEmail
structsFrom
field tostring
frommail.Address
. It is beneficial for me if I can parse tomail.Address
based on my use case. How this can be done?The text was updated successfully, but these errors were encountered: