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
and copy the downloaded dependencies to our project's folder that we are going to call vendor
with command
go mod vendor
after the dependency is downloaded, let's start to create a file call server.go
package main
import (
"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
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 parameters 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:
Top comments (2)
The
go mod vendor
command copies the downloaded dependencies into the project folder and doesn't necessarily make them recognized in the project. You could still use the dependencies in the project without having to vendor them. More about that here: go.dev/ref/mod#go-mod-vendorThank you for the correction, really appreciated!