기본 콘텐츠로 건너뛰기

golang언어에서 web 처리하기 기초



기본 파일 처리 방법
  1. 구조체를 만든다.
        type Page struct {
       Title string
          Body  []byte
        }


  2. 구조체에 구조체를 파일에 저장하는 Save() 메소드를 작성한다.
     

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

 3. 구조체를 파일을 읽어서 구조체에 저장하는 loadPage()메소드를 작성한다.
    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
    }
  4. 구조체를 저장한다.

           구조체는 초기화는 구조체 타입 + {필드명:값, 필드명:값, .... }
            구조체의 메소드 지정시 리시버를 포인터로 지정했기 때문에 &을 사용하여 주소값으로 넘긴다.  그러면 변수는 포인터 변수로 인식한다.

                       p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}
           
          구조체의 메소드를 호출
p1.save()



  5. 구조체를 호출한다.

           파일을 읽어서 구조체에 넣는다.
          p2, _ := loadPage("TestPage")

            구조체의 값을 읽어서 타입변환을 처리하여 출력한다.
fmt.Println(string(p2.Body))

  6. 이를 HTTP로 변환해도 실질적인 Response에 파일을 읽어서 처리가 가능하다.

  7. http로 변환하기 위해서는 handler 함수를 등록한다.

      http 패키지 내의  Request 구조체 안의URL 필드는 *url.URL 타입이므로      url  패키지에 URL 구조체 내의 Path 파일을 가져옵니다.

        type URL struct {
        Scheme   string
        Opaque   string    // encoded opaque data
        User     *Userinfo // username and password information
        Host     string    // host or host:port
        Path     string
        RawQuery string // encoded query values, without '?'
        Fragment string // fragment for references, without '#'
}
       
          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)
        }

  8. 핸들러를 http 서버에 등록하고  실제 호출이 오면 Listener 통해 매칭시킨다.

// 핸들러 위치에 등록
http.HandleFunc("/view/", viewHandler)
// http 서버에 대한 포트 및 주소 지정

http.ListenAndServe(":8080", nil)
   

//실제 프로그래밍...

package main

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

// response 페이지 구조체 생성

type Page struct {
Title string
Body  []byte
}

// response 페이지 파일 세이브

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

//response 페이지 읽어오기

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
}

//http 서버 핸들러 등록
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)
}

func main() {
/*
   // 페이지 생성

p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}
p1.save()
// 페이지 파일 읽어오기

p2, _ := loadPage("TestPage")
//페이지 파일 출력

fmt.Println(string(p2.Body))
*/

// 핸들러 위치에 등록
http.HandleFunc("/view/", viewHandler)
// http 서버에 대한 포트 및 주소 지정

http.ListenAndServe(":8080", nil)
}

댓글

이 블로그의 인기 게시물

golang overload 처럼 처리하기

go 언어에서는 함수명이 같을 경우 재선언 오류를 발생시킨다. 다른 메소드를 만들고 오버로드 처리하도록 설계해서 구현해야 한다. 오버로드 처리를 위해 type switch를 사용해서 들어오는 타입에 따라 메소드 호출하는 처리를 사용한다. 함수나 메소드 인자를 다양하게 처리하려면 []interface{} 로 정의해서 다양한 인자를 받아서 오버로딩 처리하면된다. package main import (  "fmt" ) func main() {  var p Person  p = Person{"dahl"}  var s string = "moon"  fmt.Println(" overloading  ", p.Overload(s))  fmt.Println(" overloading", p.Overload(nil)) } type Person struct {  name string } func (this *Person) Overload(args interface{}) string {  switch args.(type) {  case string:   return this.GetName2("moon")  case nil:   return this.GetName1()  default:   return " no match"  } } func (this *Person) GetName1() string {  return this.name } func (this *Person) GetName2(s string) string {  return this.name }

Python으로 julian date 산출하기

줄리안 일수 산출을 위해서는 윤년여부 체크를 하여 실제 그 해의 해당 일자에 대한 일수를 365 나 366 일수에 해당 일자로 전환하여 산출한다. 현재 일자를 줄리안 즉 시퀀스 일자대로 수정하는 로직이다 #일자 산출 함수 def dayconvert(month) :      convertDay = 0      dayDict = {'01':0, '02':31, '03':59, '04':90, '05':120,      '06':151, '07':181, '08':212, '09':243, '10':273,      '11':304, '12':334}      convertDay = dayDict[month]      return convertDay #줄리안데이 산출 함수 def julian(date):     year = int(date[0:4])    month = date[4:6]    day = int(date[6:8])    #윤년여부 호출   yuncheck = yunyear(year)   # 일자산출   Dday = dayconvert(month)   # 줄리안 데이 산출   Dday = Dday + day   # 유년여부 체크 및 윤년일 경우 일수조정   if yuncheck == 1:       if int(month) > 2 :            Dday = Dday + 1   # 100일 미만일 경우 포맷조정   if Dday < 100 :          Dday = '0' + str(Dday)   else :         pass   #줄리안 일자를 스트링으로 포맷 조정

Understanding golang Type . 타입이해하기...

Pre-declared Types   go 언어에서 빌드인으로 정의된 데이터 타입들.   string, number(int, uint, float...), boolean 타입들 Named vs Unnamed Type    go언어에서는 사용자 정의(type T_Int int 등)는 기본적으로 named type 으로 인식한다.   그리고  pre-declared types도 named type으로 인식한다.    unnamed type은 composited 타입들로 []int, *int 등을 별도로 인식한다.    named type 들은 메소드 정의가 가능하지만 unnamed type은 메소드를 만들 수 없다.    type Map map[string]string //this is valid func (m Map) Set(key string, value string){ m[key] = value } //this is invalid func (m map[string]string) Set(key string, value string){ m[key] = value } Underlying Type     모든 타입은 underlying type 을 가집니다.  리터럴과 declared type들은 자신의 타입을  underlying type으로 처리한다.     새로 생성되는 타입들에는 기존의 타입들이 있어야 하고 이 타입들도 항상 underlying type 을 가진다.      type Map map[string]string type SpecialMap Map SpecialMap과 Map이 underlying type은 map[string]string 이다. Assignability      //사용자 정의 타입 type Mystring string // pre-de