프로그래밍/GO

go로 web application 만들기

autostar 2021. 5. 26.
반응형

Introduction

도입

Covered in this tutorial:

이 튜토리얼에서 커버하는것

  • Creating a data structure with load and save methods
  • 로드 및 저장 방법을 사용하여 데이터 구조 생성
  • Using the net/http package to build web applications
  • net/http 패키지를 사용하여 웹 애플리케이션 구축
  • Using the html/template package to process HTML templates
  • HTML/템플릿 패키지를 사용하여 HTML 템플릿 처리
  • Using the regexp package to validate user input
  • regexp 패키지를 사용하여 사용자 입력 확인
  • Using closures
  • 클로져 사용하기

Assumed knowledge:

선수지식 

  • Programming experience
  • 프로그래밍 경험
  • Understanding of basic web technologies (HTTP, HTML)
  • 기본 웹 기술(HTTP, HTML)에 대한 이해
  • Some UNIX/DOS command-line knowledge
  • 유닉스/도스 커맨드라인 지식

 

Data Structures

데이터 구조

 

Let's start by defining the data structures. A wiki consists of a series of interconnected pages, each of which has a title and a body (the page content).

먼저 데이터 구조를 정의하는 것부터 시작하겠습니다. 위키는 일련의 상호 연결된 페이지로 구성되며, 각 페이지에는 제목과 본문(페이지 내용)이 있습니다.

Here, we define Page as a struct with two fields representing the title and body.

여기서는 제목과 본문을 나타내는 두 개의 필드가 있는 구조로 페이지를 정의합니다.

type Page struct { Title string Body []byte }



The type []byte means "a byte slice". (See Slices: usage and internals for more on slices.) The Body element is a []byte rather than string because that is the type expected by the io libraries we will use, as you'll see below.

유형 []byte는 "바이트 조각"을 의미합니다. (슬라이스에 대한 자세한 내용은 슬라이스: 사용 및 내부 참조) 본문 요소는 문자열이 아닌 []바이트입니다. 아래처럼 io 라이브러리에서 사용할 것으로 예상되는 유형이기 때문입니다.

The Page struct describes how page data will be stored in memory. But what about persistent storage? We can address that by creating a save method on Page:

페이지 구조는 페이지 데이터가 메모리에 저장되는 방법을 설명합니다. 하지만 영구 스토리지는 어떨까요? 페이지에 저장 방법을 만들어 이 문제를 해결할 수 있습니다.

func (p *Page) save() error {
	filename := p.Title + ".txt" 
    return ioutil.WriteFile(filename, p.Body, 0600)
    }

This method's signature reads: "This is a method named save that takes as its receiver p, a pointer to Page . It takes no parameters, and returns a value of type error."
이 메서드의 서명에는 "저장이라는 이름의 메서드는 수신자 p로, 페이지에 대한 포인터로 사용됩니다. 매개 변수를 사용하지 않고 형식 오류 값을 반환합니다."

 

This method will save the Page's Body to a text file. For simplicity, we will use the Title as the file name.

The save method returns an error value because that is the return type of WriteFile (a standard library function that writes a byte slice to a file).

이 메서드는 페이지의 본문을 텍스트 파일에 저장합니다. 단순성을 위해 파일 이름으로 제목을 사용합니다.
저장 메서드는 WriteFile의 반환 유형(바이트 조각을 파일에 쓰는 표준 라이브러리 함수)이기 때문에 오류 값을 반환합니다.

 

The save method returns the error value, to let the application handle it should anything go wrong while writing the file. If all goes well, Page.save() will return nil (the zero-value for pointers, interfaces, and some other types).

저장 메서드는 오류 값을 반환하여 응용 프로그램에서 파일을 쓰는 동안 오류가 발생할 경우 이를 처리하도록 합니다. 모든 것이 잘 진행되면 Page.save()는 0( 포인터, 인터페이스 및 일부 다른 유형의 0)을 반환합니다.

The octal integer literal 0600, passed as the third parameter to WriteFile, indicates that the file should be created with read-write permissions for the current user only. (See the Unix man page open(2) for details.)

WriteFile에 세 번째 매개 변수로 전달된 옥탈 정수 리터럴 0600은 파일이 현재 사용자에 대해서만 읽기-쓰기 권한으로 생성되어야 함을 나타냅니다. 자세한 내용은 Unix man 페이지 열기(2)를 참조하십시오.

 

In addition to saving pages, we will want to load pages, too:

페이지 저장 외에도 다음 페이지도 로드하려고 합니다.

func loadPage(title string) *Page { 
	filename := title + ".txt" body, _ := ioutil.ReadFile(filename)
    return &Page{
    Title: title, Body: body
    } 
   }

The function loadPage constructs the file name from the title parameter, reads the file's contents into a new variable body, and returns a pointer to a Page literal constructed with the proper title and body values.

loadPage 함수는 제목 매개 변수에서 파일 이름을 구성하고 파일의 내용을 새 변수 본문으로 읽은 다음 적절한 제목과 본문 값으로 구성된 페이지 리터럴로 포인터를 반환합니다.

Functions can return multiple values. The standard library function io.ReadFile returns []byte and error. In loadPage, error isn't being handled yet; the "blank identifier" represented by the underscore (_) symbol is used to throw away the error return value (in essence, assigning the value to nothing).

함수는 여러 값을 반환할 수 있습니다. 표준 라이브러리 함수입니다.ReadFile은 []바이트와 오류를 반환합니다. loadPage에서 에러는 아직 처리되지 않았습니다. 밑줄(_) 기호로 표시된 "공백 식별자"는 오류 반환 값(본질적으로 값을 nothing에 할당함)을 버리기 위해 사용됩니다.

But what happens if ReadFile encounters an error? For example, the file might not exist. We should not ignore such errors. Let's modify the function to return *Page and error.

그러나 ReadFile에 오류가 발생하면 어떻게 됩니까? 예를 들어 파일이 존재하지 않을 수 있습니다. 우리는 그러한 실수를 무시해서는 안 된다. *페이지와 오류를 반환하도록 기능을 수정하겠습니다.

func loadPage(title string) (*Page, error) {
	filename := title + ".txt" body, err := ioutil.ReadFile(filename) 
    if err != nil { 
    return nil, err 
    } 
    return &Page{
    Title: title, Body: body
    }, nil 
   }

Callers of this function can now check the second parameter; if it is nil then it has successfully loaded a Page. If not, it will be an error that can be handled by the caller (see the language specification for details).

이제 이 기능의 호출자는 두 번째 매개 변수를 확인할 수 있습니다. 이 매개 변수가 0이면 페이지를 성공적으로 로드했습니다. 그렇지 않은 경우, 발신자가 처리할 수 있는 오류가 됩니다(자세한 내용은 언어 사양을 참조하십시오).

At this point we have a simple data structure and the ability to save to and load from a file. Let's write a main function to test what we've written:

이 시점에서는 간단한 데이터 구조와 파일에 저장하고 파일에서 로드할 수 있습니다. 작성한 내용을 테스트하기 위한 주요 기능을 작성하겠습니다.

func main() {
	p1 := &Page{
    Title: "TestPage", Body: []byte("This is a sample Page.")
    } p1.save() p2, _ := loadPage("TestPage") 
    fmt.Println(string(p2.Body)) 
   }

After compiling and executing this code, a file named TestPage.txt would be created, containing the contents of p1. The file would then be read into the struct p2, and its Body element printed to the screen.

이 시점에서는 간단한 데이터 구조와 파일에 저장하고 파일에서 로드할 수 있습니다. 작성한 내용을 테스트하기 위한 주요 기능을 작성하겠습니다.

You can compile and run the program like this:

다음과 같이 프로그램을 컴파일하고 실행할 수 있습니다.

$ go build wiki.go $ ./wiki This is a sample Page.

(If you're using Windows you must type "wiki" without the "./" to run the program.)

(윈도우를 사용중이라면 wiki 만 사용하고 "./" 를 제외하고 프로그램을 실행하세요.)

 

Introducing the net/http package (an interlude)

Here's a full working example of a simple web server:

웹서버 샘플 예제.

// +build ignore

package main 
import ( "fmt" "log" "net/http" )
func handler(w http.ResponseWriter, r *http.Request) { 
	fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) 
} 
func main() {
	http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) 
}

The main function begins with a call to http.HandleFunc, which tells the http package to handle all requests to the web root ("/") with handler.

주 기능은 http로 호출하는 것으로 시작한다.HandleFunc - http 패키지에 핸들러를 사용하여 웹 루트("/")에 대한 모든 요청을 처리하도록 지시합니다.

It then calls http.ListenAndServe, specifying that it should listen on port 8080 on any interface (":8080"). (Don't worry about its second parameter, nil, for now.)

그런 다음 http를 호출합니다.ListenAndServe는 모든 인터페이스에서 포트 8080을 수신하도록 지정합니다(":8080") (지금 당장은 두 번째 매개 변수 nil에 대해 걱정하지 마십시오.)

This function will block until the program is terminated.

이 기능은 프로그램이 종료될 때까지 차단됩니다.

ListenAndServe always returns an error, since it only returns when an unexpected error occurs. In order to log that error we wrap the function call with log.Fatal.

ListenAndServe는 예기치 않은 오류가 발생할 때만 반환되므로 항상 오류를 반환합니다. 오류를 기록하기 위해 함수 호출을 로그로 묶습니다.치명적이다.

The function handler is of the type http.HandlerFunc. It takes an http.ResponseWriter and an http.Request as its arguments.

함수 처리기는 http 유형입니다.핸들러 펑크. 그것은 http가 필요하다.ResponseWriter 및 http.인수로 요청하십시오.

An http.ResponseWriter value assembles the HTTP server's response; by writing to it, we send data to the HTTP client.

http.ResponseWriter 값은 HTTP 서버의 응답을 취합합니다. 이 서버에 기록함으로써 HTTP 클라이언트로 데이터를 전송합니다.

An http.Request is a data structure that represents the client HTTP request. r.URL.Path is the path component of the request URL. The trailing [1:] means "create a sub-slice of Path from the 1st character to the end." This drops the leading "/" from the path name.

http.요청은 클라이언트 HTTP request.r을 나타내는 데이터 구조입니다.URL.Path는 요청 URL의 경로 구성 요소입니다. 후행 [1:]은 "첫 번째 문자에서 끝까지 경로의 하위 조각을 작성합니다"를 의미합니다. 경로 이름에서 선행 "/"가 삭제됩니다.

If you run this program and access the URL:

이 프로그램을 실행하고 URL에 액세스하는 경우:

http://localhost:8080/monkeys

the program would present a page containing:

프로그램에는 다음이 포함된 페이지가 표시됩니다.

Hi there, I love monkeys!

Using net/http to serve wiki pages

To use the net/http package, it must be imported:

net/http 패키지를 사용하려면, 임포트를 시켜야합니다.

import ( "fmt" "io/ioutil" "log" "net/http" )

Let's create a handler, viewHandler that will allow users to view a wiki page.

유저들이 위키 페이지 뷰를 볼수 있게 핸들러와 view핸들러 를 만듭니다.

It will handle URLs prefixed with "/view/".

"/view/"가 앞에 붙은 URL을 처리합니다.

func viewHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/view/"):] p, _ := loadPage(title) fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body)
    }

Again, note the use of _ to ignore the error return value from loadPage. This is done here for simplicity and generally considered bad practice. We will attend to this later.

_를 사용하여 loadPage에서 오류 반환 값을 무시하십시오. 이것은 단순성을 위해 여기서 행해지고 일반적으로 나쁜 관행으로 여겨집니다. 이 문제는 나중에 처리하겠습니다.

First, this function extracts the page title from r.URL.Path, the path component of the request URL. The Path is re-sliced with [len("/view/"):] to drop the leading "/view/" component of the request path. This is because the path will invariably begin with "/view/", which is not part of the page's title.

먼저, 이 함수는 r에서 페이지 제목을 추출합니다.요청 URL의 경로 구성 요소인 URL.Path. 경로는 [len("/view/"):]로 다시 분할되어 요청 경로의 선행 "/view/" 구성요소를 삭제합니다. 그 이유는 경로는 항상 페이지 제목의 일부가 아닌 "/view/"로 시작되기 때문입니다.

The function then loads the page data, formats the page with a string of simple HTML, and writes it to w, the http.ResponseWriter.

그러면 기능은 페이지 데이터를 로드하고, 간단한 HTML 문자열로 페이지를 포맷하고, 그것을 http에 씁니다.응답 작성기.

To use this handler, we rewrite our main function to initialize http using the viewHandler to handle any requests under the path /view/.

이 핸들러를 사용하기 위해, 우리는 /view/ 경로 아래의 모든 요청을 처리하기 위해 viewHandler를 사용하여 http를 초기화하기 위해 우리의 주요 함수를 다시 쓴다.

 

func main() {
	http.HandleFunc("/view/", viewHandler) log.Fatal(http.ListenAndServe(":8080", nil)) 
  }

 

Let's create some page data (as test.txt), compile our code, and try serving a wiki page.

Open test.txt file in your editor, and save the string "Hello world" (without quotes) in it.

페이지 데이터(test.txt)를 만들어 코드를 컴파일하고 Wiki 페이지를 서비스해 보겠습니다.
테스트를 엽니다.편집기에 txt 파일을 저장하고 "Hello world"(따옴표 없이) 문자열을 저장합니다.

$ go build wiki.go $ ./wiki

(If you're using Windows you must type "wiki" without the "./" to run the program.)

(윈도우를 사용중이라면 wiki 만 사용하고 "./" 를 제외하고 프로그램을 실행하세요.)

With this web server running, a visit to http://localhost:8080/view/test should show a page titled "test" containing the words "Hello world".

이 웹 서버를 실행하면 http://localhost:8080/view/test에 "Hello world"라는 단어가 포함된 "test" 페이지가 표시됩니다.

Editing Pages

A wiki is not a wiki without the ability to edit pages. Let's create two new handlers: one named editHandler to display an 'edit page' form, and the other named saveHandler to save the data entered via the form.

위키는 페이지를 편집할 수 있는 기능이 없는 위키가 아닙니다. 두 개의 새 핸들러를 작성하겠습니다. 하나는 '편집 페이지' 양식을 표시하는 editHandler이고 다른 하나는 양식을 통해 입력한 데이터를 저장하기 위해 editHandler를 저장하십시오.

First, we add them to main():

먼저 메인()에 추가합니다.

func main() { 
 http.HandleFunc("/view/", viewHandler) http.HandleFunc("/edit/", editHandler) http.HandleFunc("/save/", saveHandler) log.Fatal(http.ListenAndServe(":8080", nil)) 
 }

The function editHandler loads the page (or, if it doesn't exist, create an empty Page struct), and displays an HTML form.

editHandler 기능은 페이지를 로드(또는 페이지가 없는 경우 빈 페이지 구조를 생성)하고 HTML 양식을 표시합니다.

func editHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/edit/"):] p, err := loadPage(title) if err != nil {
	p = &Page{Title: title
 } 
} 
fmt.Fprintf(w, "<h1>Editing %s</h1>"+ "<form action=\"/save/%s\" method=\"POST\">"+ "<textarea name=\"body\">%s</textarea><br>"+ "<input type=\"submit\" value=\"Save\">"+ "</form>", p.Title, p.Title, p.Body) 
}

This function will work fine, but all that hard-coded HTML is ugly. Of course, there is a better way.

editHandler 기능은 페이지를 로드(또는 페이지가 없는 경우 빈 페이지 구조를 생성)하고 HTML 양식을 표시합니다.

The html/template package

The html/template package is part of the Go standard library. We can use html/template to keep the HTML in a separate file, allowing us to change the layout of our edit page without modifying the underlying Go code.

이 기능은 잘 작동하지만 하드코딩된 HTML은 모두 형편없습니다. 물론, 더 좋은 방법이 있습니다.

First, we must add html/template to the list of imports. We also won't be using fmt anymore, so we have to remove that.

html/template 패키지는 Go 표준 라이브러리의 일부입니다. HTML을 별도의 파일에 보관하기 위해 HTML/Template를 사용할 수 있으므로 기본 Go 코드를 수정하지 않고도 편집 페이지의 레이아웃을 변경할 수 있습니다.

import ( "html/template" "io/ioutil" "net/http" )

Let's create a template file containing the HTML form. Open a new file named edit.html, and add the following lines:

HTML 양식을 포함하는 템플리트 파일을 작성하겠습니다. edit.html라는 새 파일을 열고 다음 줄을 추가합니다.

<h1>Editing {{.Title}}</h1> 
<form action="/save/{{.Title}}" method="POST"> 
<div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body}}</textarea></div> 
<div><input type="submit" value="Save"></div> </form>

Modify editHandler to use the template, instead of the hard-coded HTML:

HTML 양식을 포함하는 템플리트 파일을 작성하겠습니다. edit.html라는 새 파일을 열고 다음 줄을 추가합니다.

func editHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/edit/"):] p, err := loadPage(title) if err != nil { 
p = &Page{Title: title
}
} 
t, _ := template.ParseFiles("edit.html") t.Execute(w, p) 
}

The function template.ParseFiles will read the contents of edit.html and return a *template.Template.

하드 코딩된 HTML 대신 템플릿을 사용하도록 editHandler를 수정합니다.

The method t.Execute executes the template, writing the generated HTML to the http.ResponseWriter. The .Title and .Body dotted identifiers refer to p.Title and p.Body.

메서드톤실행, http에 생성되는 HTML을 쓰기 템플릿 실행합니다.ResponseWriter.그 .Title.신체 식별자 p.를 참조하십시오에 떠다녀제목과 p.Body를 발견했다.

Template directives are enclosed in double curly braces. The printf "%s" .Body instruction is a function call that outputs .Body as a string instead of a stream of bytes, the same as a call to fmt.Printf. The html/template package helps guarantee that only safe and correct-looking HTML is generated by template actions.

 

For instance, it automatically escapes any greater than sign (>), replacing it with &gt;, to make sure user data does not corrupt the form HTML.

 

Since we're working with templates now, let's create a template for our viewHandler called view.html:

 

<h1>{{.Title}}</h1> <p>[<a href="/edit/{{.Title}}">edit</a>]</p> <div>{{printf "%s" .Body}}</div>

Modify viewHandler accordingly:

func viewHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/view/"):] p, _ := loadPage(title) 
	t, _ := template.ParseFiles("view.html") t.Execute(w, p)
}

Notice that we've used almost exactly the same templating code in both handlers. Let's remove this duplication by moving the templating code to its own function:

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
	t, _ := template.ParseFiles(tmpl + ".html") t.Execute(w, p)
}

And modify the handlers to use that function:

func viewHandler(w http.ResponseWriter, r *http.Request) { 
	title := r.URL.Path[len("/view/"):] p, _ := loadPage(title) renderTemplate(w, "view", p)
    }
    func editHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/edit/"):] p, err := loadPage(title) if err != nil {
    p = &Page{Title: title} } renderTemplate(w, "edit", p) 
    }

If we comment out the registration of our unimplemented save handler in main, we can once again build and test our program. Click here to view the code we've written so far.

Handling non-existent pages

What if you visit /view/APageThatDoesntExist? You'll see a page containing HTML. This is because it ignores the error return value from loadPage and continues to try and fill out the template with no data. Instead, if the requested Page doesn't exist, it should redirect the client to the edit Page so the content may be created:

func viewHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/view/"):] p, err := loadPage(title) if err != nil { 
http.Redirect(w, r, "/edit/"+title, http.StatusFound) 
	return 
} 
	renderTemplate(w, "view", p)
}

The http.Redirect function adds an HTTP status code of http.StatusFound (302) and a Location header to the HTTP response.

Saving Pages

The function saveHandler will handle the submission of forms located on the edit pages. After uncommenting the related line in main, let's implement the handler:

func saveHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/save/"):] body := r.FormValue("body") p := &Page{Title: title, Body: []byte(body)
    } 
     p.save() http.Redirect(w, r, "/view/"+title, http.StatusFound)
     }

The page title (provided in the URL) and the form's only field, Body, are stored in a new Page. The save() method is then called to write the data to a file, and the client is redirected to the /view/ page.

The value returned by FormValue is of type string. We must convert that value to []byte before it will fit into the Page struct. We use []byte(body) to perform the conversion.

Error handling

There are several places in our program where errors are being ignored. This is bad practice, not least because when an error does occur the program will have unintended behavior. A better solution is to handle the errors and return an error message to the user. That way if something does go wrong, the server will function exactly how we want and the user can be notified.

First, let's handle the errors in renderTemplate:

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
	t, err := template.ParseFiles(tmpl + ".html") if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
    return
    } 
    err = t.Execute(w, p) if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
	} 
}

The http.Error function sends a specified HTTP response code (in this case "Internal Server Error") and error message. Already the decision to put this in a separate function is paying off.

Now let's fix up saveHandler:

func saveHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/save/"):] body := r.FormValue("body") p := &Page{Title: title, Body: []byte(body)}
err := p.save() if err != nil { 
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} 
http.Redirect(w, r, "/view/"+title, http.StatusFound) 
}

Any errors that occur during p.save() will be reported to the user.

Template caching

There is an inefficiency in this code: renderTemplate calls ParseFiles every time a page is rendered. A better approach would be to call ParseFiles once at program initialization, parsing all templates into a single *Template. Then we can use the ExecuteTemplate method to render a specific template.

First we create a global variable named templates, and initialize it with ParseFiles.

var templates = template.Must(template.ParseFiles("edit.html", "view.html"))

The function template.Must is a convenience wrapper that panics when passed a non-nil error value, and otherwise returns the *Template unaltered. A panic is appropriate here; if the templates can't be loaded the only sensible thing to do is exit the program.

The ParseFiles function takes any number of string arguments that identify our template files, and parses those files into templates that are named after the base file name. If we were to add more templates to our program, we would add their names to the ParseFiles call's arguments.

We then modify the renderTemplate function to call the templates.ExecuteTemplate method with the name of the appropriate template:

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
	err := templates.ExecuteTemplate(w, tmpl+".html", p) if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
	} 
}

Note that the template name is the template file name, so we must append ".html" to the tmpl argument.

Validation

As you may have observed, this program has a serious security flaw: a user can supply an arbitrary path to be read/written on the server. To mitigate this, we can write a function to validate the title with a regular expression.

First, add "regexp" to the import list. Then we can create a global variable to store our validation expression:

var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")

The function regexp.MustCompile will parse and compile the regular expression, and return a regexp.Regexp. MustCompile is distinct from Compile in that it will panic if the expression compilation fails, while Compile returns an error as a second parameter.

Now, let's write a function that uses the validPath expression to validate path and extract the page title:

func getTitle(w http.ResponseWriter, r *http.Request) (string, error) {
m := validPath.FindStringSubmatch(r.URL.Path) if m == nil {
http.NotFound(w, r) return "", errors.New("invalid Page Title")
	} 
return m[2], nil // The title is the second subexpression. 
}

If the title is valid, it will be returned along with a nil error value. If the title is invalid, the function will write a "404 Not Found" error to the HTTP connection, and return an error to the handler. To create a new error, we have to import the errors package.

Let's put a call to getTitle in each of the handlers:

func viewHandler(w http.ResponseWriter, r *http.Request) {
	title, err := getTitle(w, r) if err != nil {
	return 
} 
	p, err := loadPage(title) if err != nil {
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
	return 
} 
	renderTemplate(w, "view", p)}
func editHandler(w http.ResponseWriter, r *http.Request) {
	title, err := getTitle(w, r) if err != nil {
	return 
	} 
	p, err := loadPage(title) if err != nil { p = &Page{Title: title
	}
} 
	renderTemplate(w, "edit", p) 
}
func saveHandler(w http.ResponseWriter, r *http.Request) { 
	title, err := getTitle(w, r) if err != nil { 
	return 
} 
	body := r.FormValue("body") p := &Page{Title: title, Body: []byte(body)
} 
	err = p.save() if err != nil { 
	http.Error(w, err.Error(), http.StatusInternalServerError) 
	return 
} 
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}

Introducing Function Literals and Closures

Catching the error condition in each handler introduces a lot of repeated code. What if we could wrap each of the handlers in a function that does this validation and error checking? Go's function literals provide a powerful means of abstracting functionality that can help us here.

First, we re-write the function definition of each of the handlers to accept a title string:

func viewHandler(w http.ResponseWriter, r *http.Request, title string) 
func editHandler(w http.ResponseWriter, r *http.Request, title string) 
func saveHandler(w http.ResponseWriter, r *http.Request, title string)

Now let's define a wrapper function that takes a function of the above type, and returns a function of 

type http.HandlerFunc (suitable to be passed to the function http.HandleFunc):

func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
// Here we will extract the page title from the Request, 
// and call the provided handler 'fn'
	} 
}

The returned function is called a closure because it encloses values defined outside of it. In this case, the variable fn (the single argument to makeHandler) is enclosed by the closure. The variable fn will be one of our save, edit, or view handlers.

Now we can take the code from getTitle and use it here (with some minor modifications):

func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := validPath.FindStringSubmatch(r.URL.Path) if m == nil {
http.NotFound(w, r) return } fn(w, r, m[2])
} 
}

The closure returned by makeHandler is a function that takes an http.ResponseWriter and http.Request (in other words, an http.HandlerFunc). The closure extracts the title from the request path, and validates it with the validPath regexp. If the title is invalid, an error will be written to the ResponseWriter using the http.NotFound function. If the title is valid, the enclosed handler function fn will be called with the ResponseWriter, Request, and title as arguments.

Now we can wrap the handler functions with makeHandler in main, before they are registered with the http package:

func main() { 
	http.HandleFunc("/view/", makeHandler(viewHandler)) http.HandleFunc("/edit/", makeHandler(editHandler)) http.HandleFunc("/save/", makeHandler(saveHandler)) log.Fatal(http.ListenAndServe(":8080", nil))
}

Finally we remove the calls to getTitle from the handler functions, making them much simpler:

func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title) if err != nil { 
	http.Redirect(w, r, "/edit/"+title, http.StatusFound)
    return 
} 
	renderTemplate(w, "view", p) 
}
func editHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title) if err != nil { 
	p = &Page{Title: title} 
} 
renderTemplate(w, "edit", p) 
}
func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
body := r.FormValue("body") p := &Page{Title: title, Body: []byte(body)
} 
err := p.save() if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) 
	return
    } 
    http.Redirect(w, r, "/view/"+title, http.StatusFound) 

Try it out!

Recompile the code, and run the app:

$ go build wiki.go $ ./wiki

Visiting http://localhost:8080/view/ANewPage should present you with the page edit form. You should then be able to enter some text, click 'Save', and be redirected to the newly created page.

Other tasks

Here are some simple tasks you might want to tackle on your own:

  • Store templates in tmpl/ and page data in data/.
  • Add a handler to make the web root redirect to /view/FrontPage.
  • Spruce up the page templates by making them valid HTML and adding some CSS rules.
  • Implement inter-page linking by converting instances of [PageName] to
    <a href="/view/PageName">PageName</a>. (hint: you could use regexp.ReplaceAllFunc to do this)
반응형

댓글