Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 19, 2021 03:06 pm GMT

Build a simple API with Golang echo framework

Hi everyone, in this article i'm going to show tutorial on how to create simple API with Echo Golang framework

First thing that we need to do is to create project in golang by running this command

go mod init {your-package name}

example

go mod init github.com/yanoandri/simple-golang-echo

your package name could be anything, but for this tutorial i'm using the url of my github repos for later

after running the command, there will be a file call go.mod and this time we will run this command to get echo dependencies

go get github.com/labstack/echo/v4

to make this dependencies recognized throughout the project run

go mod vendor

after the dependency is downloaded, let's start to create a file call server.go

package mainimport (    "net/http"    "github.com/labstack/echo")type HelloWorld struct {    Message string `json:"message"`}func main() {    e := echo.New()    e.GET("/hello", Greetings)    e.Logger.Fatal(e.Start(":3000"))}func Greetings(c echo.Context) error {    return c.JSON(http.StatusOK, HelloWorld{        Message: "Hello World",    })}

let's run the API that we just created, by command

go run server.go

Successfully run echo

Then We will test the API by request to http://localhost:3000/hello the response will be

{"message":"Hello World"}

Now, let's head back and handle any paramters or query inside the url, by modifying some of the line in the main function. let's add the function to handle query and parameters

func GreetingsWithParams(c echo.Context) error {    params := c.Param("name")    return c.JSON(http.StatusOK, HelloWorld{        Message: "Hello World, my name is " + params,    })}func GreetingsWithQuery(c echo.Context) error {    query := c.QueryParam("name")    return c.JSON(http.StatusOK, HelloWorld{        Message: "Hello World i'm using queries and my name is " + query,    })}

Then in the main function, add this two line

e.GET("/hello/:name", GreetingsWithParams)e.GET("/hello-queries", GreetingsWithQuery)

let's test it again by requesting the url with parameters
localhost:3000/hello/yano

{"message":"Hello World, my name is yano"}

and the second request using query with http://localhost:3000/hello-queries?name=yano

{"message":"Hello World i'm using queries and my name is yano"}

That's it for this tutorial, thank you for reading and happy coding :)

Source:


Original Link: https://dev.to/yanoandri/build-a-simple-api-with-golang-echo-framework-320g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To