Search code examples
htmlnode.jsjsongogo-fiber

how can I validate and process html form (taking in inpute from the ui login interface) using fiber framework golang programming language


please help me to take input with fiber golang framework

<form action="/" method="POST" novalidate>
    <div>
        <p><label>Your email:</label></p>
        <p><input type="email" name="email"></p>
    </div>
    <div>
        <p><label>Your message:</label></p>
        <p><textarea name="content"></textarea></p>
    </div>
    <div>
        <input type="submit" value="Send message">
    </div>
</form> ```

Solution

  • You can use c.FormValue for simple forms, and keep in mind that the return value is always a string. So if you want to send integers as well you will have to manually convert them to integers in handlers. for more complex forms like sending files you can use c.MultipartForm.

    func main() {
        // create new fiber instance  and use across whole app
        app := fiber.New()
    
        // middleware to allow all clients to communicate using http and allow cors
        app.Use(cors.New())
    
        // homepage
        app.Get("/", func(c *fiber.Ctx) error {
            // rendering the "index" template with content passing
            return c.Render("index", fiber.Map{})
        })
    
        // app.Post because method="POST"
        // "/" because action="/"
        app.Post("/", handleFormUpload)
    
        // start dev server on port 4000
        log.Fatal(app.Listen(":4000"))
    }
    
    func handleFormUpload(c *fiber.Ctx) error {
        email := c.FormValue("email")
        content := c.FormValue("content")
    
        fmt.Println(email, content)
        return c.JSON(fiber.Map{"status": 201, "message": "Created!"})
    }