반응형

Golang, 간단한 Go API 서버 예제

 

글. 수알치 오상문


예제 코드는 다음과 같습니다. 

// simple_api/main.go
//
// 패키징 & 빌드
// go mod init simple_api
// go mod tidy
// go build .
//
// 실행: ./simple_api
//
// 웹 접속 예
// http://localhost --> Homepage
// http://localhost/hello --> Hello, World!
// http://localhost/double --> 도움말 반환
// http://localhost/double/100 --> 100 두 배는 200

package main

import (
    "fmt"
    "net/http"
    "strconv"

    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
)

func main() {
    // Echo instance
    e := echo.New()

    // Middleware
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())
    e.Pre(middleware.RemoveTrailingSlash()) // localhost/hello/ 접근 시 localhost/hello 처리

    // Routes
    e.GET("/", home)
    e.GET("/hello", hello)
    e.GET("/hello/:name", helloWithName)
    e.GET("/double/:num", doubleNumber)
    e.GET("/double", showHelpDouble)

    // Start server
    e.Logger.Fatal(e.Start(":80"))
}

// Handler for "/"
func home(c echo.Context) error {
    return c.String(http.StatusOK, "Homepage")
}

// Handler for "/hello"
func hello(c echo.Context) error {
    return c.String(http.StatusOK, "Hello, World!")
}

// Handler for "/hello/:name"
func helloWithName(c echo.Context) error {
    name := c.Param("name") // Retrieve the value of "name" parameter from the URL
    return c.String(http.StatusOK, "Hello, "+name+"!")
}

// Handler for "/double/:num"
func doubleNumber(c echo.Context) error {
    numParam := c.Param("num")         // "num" 파라미터
    num, err := strconv.Atoi(numParam) // 파라미터 값을 정수로 변경
    if err != nil {
        return c.String(http.StatusBadRequest, "Invalid number")
    }

    doubled := num + num // 두 배 계산
    response := fmt.Sprintf("%d 두 배는 %d", num, doubled)
    return c.String(http.StatusOK, response)
}

// Handler for "/double" (도움말 반환)
func showHelpDouble(c echo.Context) error {
    helpMessage := "double API.\n사용: /page/:num\n예제: /page/5 접근 시 '10 두 배는 20' 반환"
    return c.String(http.StatusOK, helpMessage)
}

 

[실행 화면] ./simple_api

 

[접속 화면] http://localhost/double/5

 

 

반응형

+ Recent posts