Skip to content

1. RESTful API: Hello world

Mahir edited this page Jul 23, 2022 · 3 revisions

Final result:

Endpoint: [HTTP GET] http://localhost:1200/api/v1/greetings

Response message: {"msg": "Hello world!"}

HTTP response code: 200

Create a project, build, run

  • Create a new project folder myapi
  • Create controller folder
  • Create a file greetings.go inside controller folder
  • Write a function Greetings to greetings.go file
package controller

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/pilinux/gorest/lib/renderer"
)

func Greetings(c *gin.Context) {
	renderer.Render(c, gin.H{"msg": "Hello world!"}, http.StatusOK)
}

  • Add the router to the main function in main.go file
package main

import (
	"fmt"

	"myapi/controller"

	"github.com/gin-gonic/gin"
	"github.com/pilinux/gorest/lib/middleware"
)

func main() {
	router, err := SetupRouter()
	if err != nil {
		fmt.Println(err)
		return
	}
	err = router.Run(":" + "1200")
	if err != nil {
		fmt.Println(err)
		return
	}
}

// SetupRouter ...
func SetupRouter() (*gin.Engine, error) {
	router := gin.Default()

	origin := "*"
	credentials := "true"
	headers := "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With"
	methods := "GET, POST, PUT, PATCH, DELETE"
	maxAge := "300"

	router.Use(middleware.CORS(
		origin,
		credentials,
		headers,
		methods,
		maxAge,
	))
	// For gorest <= v1.4.5
	// router.Use(middleware.CORS())

	// API:v1
	v1 := router.Group("/api/v1/")
	{
		v1.GET("greetings", controller.Greetings)
	}

	return router, nil
}

  • Create a Go module, build and start the app.

go mod init myapi

go mod tidy -compat=1.17

go build

chmod +x myapi

./myapi

Project file structure

myapi
│--- main.go
│--- go.mod
│--- go.sum
│
└─── controller
│    └--- greetings.go
Clone this wiki locally