Go web7. Pat, Render, Negroni

JINSOO PARK·2021년 10월 27일

Go 로 만드는 웹

목록 보기
6/16

Pat

package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"time"

	"github.com/gorilla/pat"
)

type User struct {
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
}

func getUserInfoHandler(w http.ResponseWriter, r *http.Request) {
	user := User{Name: "jinsoo", Email: "jinzza456@gmail.com"}

	w.Header().Add("Content-type", "application/json")
	w.WriteHeader(http.StatusOK)
	data, _ := json.Marshal(user)
	fmt.Fprint(w, string(data))
}

func addUserHandler(w http.ResponseWriter, r *http.Request) {
	user := new(User)
	err := json.NewDecoder(r.Body).Decode(user)
	// json을 읽어와서 user에 값을 채워준다.
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(w, err)
		return
	}
	user.CreatedAt = time.Now()
	w.Header().Add("Content-type", "application/json")
	w.WriteHeader(http.StatusOK)
	data, _ := json.Marshal(user)
	fmt.Fprint(w, string(data))
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.New("Hello").ParseFiles("templates/hello.tmpl")
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(w, err)
		return
	}
	tmpl.ExecuteTemplate(w, "hello.tmpl", "jinsoo")
}

func main() {
	mux := pat.New()
	// 고릴라의 팻 패키지 사용

	mux.Get("/users", getUserInfoHandler)
	// 매서드를 앞에 써줌
	mux.Post("/users", addUserHandler)
	mux.Get("/hello", helloHandler)

	http.ListenAndServe(":3000", mux)
}


Render

ex)

package main

import (
	"encoding/json"
	"net/http"
	"time"

	"github.com/gorilla/pat"
	"github.com/unrolled/render"
)

var rd *render.Render

// 랜더형 포인터 rd 선언

type User struct {
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
}

func getUserInfoHandler(w http.ResponseWriter, r *http.Request) {
	user := User{Name: "jinsoo", Email: "jinzza456@gmail.com"}

	rd.JSON(w, http.StatusOK, user)
	// 아래의 내용이 위의 한줄로 끝이남
	// w.Header().Add("Content-type", "application/json")
	// w.WriteHeader(http.StatusOK)
	// data, _ := json.Marshal(user)
	// fmt.Fprint(w, string(data))
}

func addUserHandler(w http.ResponseWriter, r *http.Request) {
	user := new(User)
	err := json.NewDecoder(r.Body).Decode(user)
	// json을 읽어와서 user에 값을 채워준다.
	if err != nil {
		rd.Text(w, http.StatusBadRequest, err.Error())
		// 에러일 경우 에러 메세지
		// w.WriteHeader(http.StatusBadRequest)
		// fmt.Fprint(w, err)
		return
	}
	user.CreatedAt = time.Now()
	rd.JSON(w, http.StatusOK, user)
	// 아래의 내용이 위의 한줄로 끝이남
	// w.Header().Add("Content-type", "application/json")
	// w.WriteHeader(http.StatusOK)
	// data, _ := json.Marshal(user)
	// fmt.Fprint(w, string(data))
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
	// tmpl, err := template.New("Hello").ParseFiles("templates/hello.tmpl")
	// if err != nil {
	// 	w.WriteHeader(http.StatusBadRequest)
	// 	fmt.Fprint(w, err)
	// 	return
	// }
	// tmpl.ExecuteTemplate(w, "hello.tmpl", "jinsoo")

	rd.HTML(w, http.StatusOK, "hello", "jinsoo")
	//탬플릿을 만들때 w, status넣고,
	//확장자 없이 탬플릿명, 인스턴스
}

func main() {
	rd = render.New()
	// rd = render.New(reder.Options{
	//	Directory: "templates",
	// 	Extensions: []string{".html", ".tmpl"}
	// })// 탬플릿의 확장자를 추가할때
	mux := pat.New()
	// 고릴라의 팻 패키지 사용

	mux.Get("/users", getUserInfoHandler)
	// 매서드를 앞에 써줌
	mux.Post("/users", addUserHandler)
	mux.Get("/hello", helloHandler)

	http.ListenAndServe(":3000", mux)
}



레이아웃 만들기

ex) body.html

Name: {{.Name}}
Email: {{.Email}}

ex) hello.html

<html>
<head>
<titel>{{partial "title"}}// 타이틀 탬플릿</title>
</head>
<body>
Hello World 
{{ yield }} // 현재 인풋이 들어감
</body>
</html>

ex) title-body.html

Partial Go in Web

ex) main

package main

import (
	"encoding/json"
	"net/http"
	"time"

	"github.com/gorilla/pat"
	"github.com/unrolled/render"
	// "github.com/urfave/negroni"
)

var rd *render.Render

// 랜더형 포인터 rd 선언

type User struct {
	Name      string    `json:"name"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
}

func getUserInfoHandler(w http.ResponseWriter, r *http.Request) {
	user := User{Name: "jinsoo", Email: "jinzza456@gmail.com"}

	rd.JSON(w, http.StatusOK, user)
}

func addUserHandler(w http.ResponseWriter, r *http.Request) {
	user := new(User)
	err := json.NewDecoder(r.Body).Decode(user)
	// json을 읽어와서 user에 값을 채워준다.
	if err != nil {
		rd.Text(w, http.StatusBadRequest, err.Error())
		// 에러일 경우 에러 메세지
		return
	}
	user.CreatedAt = time.Now()
	rd.JSON(w, http.StatusOK, user)

}
func helloHandler(w http.ResponseWriter, r *http.Request) {
	user := User{Name: "jinsoo", Email: "jinzza456@gmail.com"}

	rd.HTML(w, http.StatusOK, "body", user)
	// user 내용을 body로
}

func main() {
	rd = render.New(render.Options{
		Directory:  "templates",
		Extensions: []string{".html", ".tmpl"},
		// 탬플릿의 확장자를 추가할때
		Layout: "hello",
		// 레이아웃 추가
	})

	mux := pat.New()
	// 고릴라의 팻 패키지 사용

	mux.Get("/users", getUserInfoHandler)
	// 매서드를 앞에 써줌
	mux.Post("/users", addUserHandler)
	mux.Get("/hello", helloHandler)

	http.ListenAndServe(":3000", mux)
}



Negroni

데코레이터 핸들러를 만들때 대표적으로 많이쓰이는 부가기능들을 제공하는 패키지

ex) index.html

<html>
    <head>
        <title>Go in Web jinsoo</title>
    </head>
    <body>
        <h1>Hello Go in Park</h1>
    </body>
</html>

ex) main

func main() {
	rd = render.New(render.Options{
		Directory:  "templates",
		Extensions: []string{".html", ".tmpl"},
		// 탬플릿의 확장자를 추가할때
		Layout: "hello",
		// 레이아웃 추가
	})

	mux := pat.New()
	// 고릴라의 팻 패키지 사용

	mux.Get("/users", getUserInfoHandler)
	// 매서드를 앞에 써줌
	mux.Post("/users", addUserHandler)
	mux.Get("/hello", helloHandler)

	n := negroni.Classic()
	n.UseHandler(mux)
	// 다른 핸들러를 넣어주면 래핑해줌 (데코레이터)
	http.ListenAndServe(":3000", n)
}
profile
개린이

0개의 댓글