...

Source file src/gitlab.com/tslocum/sriracha/web.go

Documentation: gitlab.com/tslocum/sriracha

     1  package sriracha
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  	"strings"
     8  
     9  	"github.com/h2non/filetype"
    10  )
    11  
    12  const indexPage = `
    13  <form method="post" action="/upload" enctype="multipart/form-data">
    14  <input type="file" name="file"><input type="submit">
    15  </form>
    16  `
    17  
    18  func (s *sriracha) handleIndex(w http.ResponseWriter, r *http.Request) {
    19  	w.Header().Set("Content-Type", "text/html; charset=utf-8")
    20  
    21  	fmt.Fprintf(w, indexPage)
    22  }
    23  
    24  func (s *sriracha) uploadFile(w http.ResponseWriter, r *http.Request) {
    25  	r.ParseMultipartForm(10 << 20)
    26  
    27  	file, header, err := r.FormFile("file")
    28  	if err != nil {
    29  		log.Println("failed to get uploaded file")
    30  		return
    31  	}
    32  	defer file.Close()
    33  
    34  	fileTypeResult, err := filetype.MatchReader(file)
    35  	if err != nil || fileTypeResult.MIME.Value == "" {
    36  		log.Fatal("failed to get file type")
    37  	}
    38  	mime := strings.ToLower(strings.TrimSpace(fileTypeResult.MIME.Value))
    39  
    40  	attachment, err := s.handleAttachment(file, header.Size, mime)
    41  	if err != nil {
    42  		log.Fatalf("failed to attach file: %s", err)
    43  	}
    44  
    45  	log.Println(attachment)
    46  }
    47  
    48  func (s *sriracha) runWebServer() error {
    49  	http.HandleFunc("/", s.handleIndex)
    50  	http.HandleFunc("/upload", s.uploadFile)
    51  
    52  	return http.ListenAndServe(":8080", nil)
    53  }
    54  

View as plain text