goweb.go 7.33 KB
Newer Older
IBM Bluemix's avatar
IBM Bluemix committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
package main

import (
	"html/template"
	"net/http"
	"log"
	"os"
	"strconv"
	"fmt"
)

type Results struct {
  Title    string // Indicates success or failure
  Message  string // the result message
  Details  string // the details of the message
}

const (
  DEFAULT_PORT = "4001"

  primesHeader = `
<html>
  <head>
    <title>Go Sample App - {{.Title}}</title>
    <link rel="stylesheet" href="/stylesheets/style.css">
  </head>

  <body>

    <h1>{{.Title}}</h1>
    <p><div>{{.Message}}</div></p>
    <div>
`

  primesFooter = `
    </div>
    <p><div><a href="/">Back home</a></div></p>

  </body>
</html>
`
)

var resultsTemplate = template.Must(template.ParseFiles("templates/results.html"))
var primesHeaderTemplate = template.Must(template.New("header").Parse(primesHeader))
var primesFooterTemplate = template.Must(template.New("footer").Parse(primesFooter))


// Display the index html page
//
func publicHandler(w http.ResponseWriter, r *http.Request) {
  log.Println(">> publicHandler")
  defer log.Println("<< publicHandler")

  if r.Method != "GET" {
    w.WriteHeader(http.StatusMethodNotAllowed)
    return
  }

  path := "public" + r.URL.Path
  if path == "public/" {
    path = "public/index.html"
  }
  log.Printf("Serving file: %+v\n", path)
  http.ServeFile(w, r, path)
}


// Put in another file and make it a library
//
type InvalidArgument uint

func (n InvalidArgument) Error() string {
  return fmt.Sprintf("Invalid argument number %d", n)
}

type Factor struct {
  Num uint64
  Pow uint
}

// Return a sorted array of Factor, where each element is the
// prime factor with the associated power
//
func PrimeFactors(n uint64) ([]Factor, error) {
  if n < 2 {
    return nil, InvalidArgument(n)
  }

  factors := make([]Factor, 0)

  var i uint
  for i=0; n%2 == 0; i++ { n /= 2 }
  if i > 0 { factors = append(factors, Factor{Num: 2, Pow:i}) }

  for p:=uint64(3); (p*p) <= n; p+=2 {

    for i=0; n%p == 0; i++ { n /= p }
    if i > 0 { factors = append(factors, Factor{Num: p, Pow:i}) }

  }

  if n > 1 { factors = append(factors, Factor{Num: n, Pow:1}) }

  return factors, nil
}

// Calculate first n prime numbers and send them
// over a channel
//
func FirstNPrimeNumbers(n uint, ch chan uint64) (error) {
  log.Println(">> FirstNPrimeNumbers")
  defer log.Println("<< FirstNPrimeNumbers")

  if n < 3 {
    return InvalidArgument(n)
  }

  primes := make([]uint64, n)
  primes[0] = 2
  primes[1] = 3
  primes[2] = 5
  cprime := uint64(7)

  ch <- primes[0]
  ch <- primes[1]
  ch <- primes[2]

  for i:=uint(3); i<n; cprime+=2 {
    if (cprime%5) != 0 {
      isprime := true
      for p := 0; (primes[p]*primes[p]) <= cprime; p++ {
        if (cprime%primes[p]) == 0 {
          isprime = false
          break
        }
      }
      if isprime {
        primes[i] = cprime
        i++
        ch <- cprime
      }
    }
  }
  return nil
}

func prettyPrintPrimeFactors(n uint64, f []Factor) string {
  s := fmt.Sprintf("Prime Factors of %+v = ", n)
  for i, _ := range f {
    if i==0 {
      s += fmt.Sprintf("%v^%v", f[i].Num, f[i].Pow)
    } else {
      s += fmt.Sprintf(" * %v^%v", f[i].Num, f[i].Pow)
    }
  }
  return s
}



// Rest handler to get prime factors of a number
// GET /primefactors?number=[the number]
//
func primeFactorsHandler(w http.ResponseWriter, r *http.Request) {
  log.Println(">> primeFactorsHandler")
  defer log.Println("<< primeFactorsHandler")

  if r.Method != "POST" {
    w.WriteHeader(http.StatusMethodNotAllowed)
    return
  }

  num_s := r.FormValue("number")
  log.Printf("Got number from input form: %+v\n", num_s)
  var results *Results
  if num, err := strconv.Atoi(num_s); err==nil {
    // calculate prime factors
    if num > 0 {
      if factors, err := PrimeFactors(uint64(num)); err == nil {
        ss := prettyPrintPrimeFactors(uint64(num), factors)
        results = &Results{Title: "Success", Message: ss}
      } else {
        results = &Results{Title: "Error",
                           Message: fmt.Sprintf("Cannot calculate prime factors of %+v", num),
                           Details: err.Error()}
      }
    } else {
      results = &Results{Title: "Error",
                         Message: fmt.Sprintf("Cannot calculate prime factors of %+v", num),
                         Details: "It must be greather than zero."}
    }
  } else {
    results = &Results{Title: "Error",
                       Message: "Invalid number",
                       Details: err.Error()}
  }
  renderResults(w, results)
}

func primeNumbersHandler(w http.ResponseWriter, r *http.Request) {
  log.Println(">> primeNumbersHandler")
  defer log.Println("<< primeNumbersHandler")

  if r.Method != "POST" {
    w.WriteHeader(http.StatusMethodNotAllowed)
    return
  }

  num_s := r.FormValue("limit")
  log.Printf("Got limit from input form: %+v\n", num_s)
  var results *Results
  if num, err := strconv.Atoi(num_s); err==nil {
    // calculate first limit prime numbers
    if num > 0 {
      ch := make(chan uint64, 1)
      quit := make(chan *Results, 1)
      go func() {
        if err := FirstNPrimeNumbers(uint(num), ch); err != nil {
          results = &Results{Title: "Error",
                             Message: fmt.Sprintf("Cannot calculate first %+v prime numbers", num),
                             Details: err.Error()}
        }
        // signal the normal end of calculation
        quit <- results
      }()

      writeHead := true
      tab := 0
      for {
        select {
          case v := <- ch:
            if writeHead {
              // do write header
              primesHeaderTemplate.Execute(w, &Results{Title: "Success", Message: fmt.Sprintf("First %+v prime numbers:\n", num)})
              writeHead = false
            }
            fmt.Fprintf(w, "%+v  ", v)
            if tab++; tab > 14 {
              fmt.Fprintf(w, "<br>")
              tab = 0
            }

          case res := <- quit:
            if res == nil {
              primesFooterTemplate.Execute(w, nil)
            } else {
              renderResults(w, results)
            }
            return
        }
      }

    } else {
      results = &Results{Title: "Error",
                         Message: fmt.Sprintf("Cannot calculate first %+v prime numbers", num),
                         Details: "Limit must be greather than zero."}
    }
  } else {
    results = &Results{Title: "Error",
                       Message: "Invalid number",
                       Details: err.Error()}
  }
  if results != nil {
    log.Printf("Renedring results %+v\n", results) // debug only
    renderResults(w, results)
  }
}

func renderResults(w http.ResponseWriter, results *Results) {
  log.Println(">> renderResults")
  defer log.Println("<< renderResults")

  if err := resultsTemplate.ExecuteTemplate(w, "results.html", results); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
  }
}

func main() {
  // Configure the standard logger
  log.SetFlags(log.Lmicroseconds|log.Ldate|log.Lshortfile)

  log.Println(">> GoWeb")
  defer log.Println("<< GoWeb")

  var port string
  if port = os.Getenv("VCAP_APP_PORT"); len(port)==0 {
    log.Printf("Warning, VCAP_APP_PORT not set. Defaulting to %+v\n", DEFAULT_PORT)
    port = DEFAULT_PORT
  }

  http.HandleFunc("/primefactors", primeFactorsHandler)
  http.HandleFunc("/primenumbers", primeNumbersHandler)
  http.HandleFunc("/", publicHandler)

  log.Printf("Starting GoWeb on port %+v\n", port)
  http.ListenAndServe(":" + port, nil)
}