ocr-server.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package main
  2. import (
  3. "html/template"
  4. "log"
  5. "net/http"
  6. "fmt"
  7. "os"
  8. "time"
  9. "io"
  10. "crypto/md5"
  11. "strconv"
  12. "github.com/otiai10/gosseract"
  13. )
  14. func upload(w http.ResponseWriter, r *http.Request) {
  15. if r.Method == "GET" {
  16. crutime := time.Now().Unix()
  17. h := md5.New()
  18. io.WriteString(h, strconv.FormatInt(crutime, 10))
  19. token := fmt.Sprintf("%x", h.Sum(nil))
  20. t, _ := template.ParseFiles("upload.html")
  21. t.Execute(w, token)
  22. } else {
  23. r.ParseMultipartForm(32 << 20)
  24. file, handler, err := r.FormFile("uploadfile")
  25. if err != nil {
  26. fmt.Println(err)
  27. return
  28. }
  29. defer file.Close()
  30. f, err := os.OpenFile("test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
  31. if err != nil {
  32. fmt.Println(err)
  33. return
  34. }
  35. defer f.Close()
  36. io.Copy(f, file)
  37. sc := "test/"+handler.Filename
  38. out := gosseract.Must(gosseract.Params{
  39. Src: sc,
  40. Languages: "eng",
  41. })
  42. fmt.Fprintf(w, out)
  43. os.Remove(sc)
  44. }
  45. }
  46. func main() {
  47. os.Mkdir("test", os.ModePerm)
  48. http.HandleFunc("/", upload)
  49. err := http.ListenAndServe(":8080", nil) // setting listening port
  50. if err != nil {
  51. log.Fatal("ListenAndServe: ", err)
  52. }
  53. }