Golang Rest-Api 기본 (gorilla/mux)

Divan·2022년 6월 8일
1
post-thumbnail

해당 자료는 Cloud-Native-programming-with-Golang 내용을 정리하고자 작성하였습니다. (소스코드는 해당 링크에 있습니다.)

우선 go 언어에서 프로그램의 시작점은 main pakage의 main함수가 시작점이 된다.
아래 코드에서는 rest package를 import 하고 ServeApi 메서드를 호출합니다.

package main
import (
	"fmt"
	"github.com/SeoEunkyo/golang_mq/rest"
)

func main (){
	rest.ServeAPI("127.0.0.1:8888")
	fmt.Println("Rest API Server Start")
}

호출 된 Service메서드를 살펴보면 Route를 매핑시켜주는 작업을 하는것을 확인 가능하다.

package rest

import (
	"fmt"
	"net/http"
	"time"
	"github.com/gorilla/mux"
)
func ServeAPI(listenAddr string){
	r := mux.NewRouter()
	r.Methods("get").Path("/").Handler(&IndexHandler{})
	r.Methods("get").Path("/event/{eventID}/booking").Handler(&CreateBookingHandler{})

	srv := http.Server{
		Handler:      r,
		Addr:         listenAddr,
		WriteTimeout: 2 * time.Second,
		ReadTimeout:  1 * time.Second,
	}
	
	err := srv.ListenAndServe()
	if err != nil {
		fmt.Println("err : " , err)
	}
}

여기서 .Handler()의 인자로는 http.Hander가 요구 되어진다.

그럼 http.Handler를 어떻게 정의를 확인해보자. http.Handler는 ServerHTTP 메서드를 포함한 interface이다 그렇기에 r.Methods("get").Path("/").Handler(&IndexHandler{}) 에서 IndexHandler는 필수로 ServerHTTP메서드를 작성해야한다.

아래 코드를 보면 IndexHandler구조체가 ServeHTTP를 포함하는것을 확인 가능하다.

package rest
import (
	"net/http"
)
type IndexHandler struct {
	 
}
func (h *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request){
	w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write( []byte("Server is running "))
}
profile
하루 25분의 투자

0개의 댓글