An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
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
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 parameterslocalhost: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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To