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
반응형
'Go (Golang)' 카테고리의 다른 글
Golang 에러 처리, 에러 생성, 예외 처리 (1) | 2023.12.28 |
---|---|
go 소스 코드에서 C 코드를 이용하기 (1) | 2023.12.26 |
다른 언어에서 Go 함수 호출하기 (C언어 .so 파일 이용) (1) | 2023.12.23 |
golang, 피보나치 수열 함수 예제 2 (0) | 2023.12.10 |
golang, 피보나치 수열 함수 예제 (0) | 2023.12.10 |