resource.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package resource
  2. import (
  3. "net/http"
  4. )
  5. type OneResource struct {
  6. Path string
  7. Ctype string
  8. Bytes []byte
  9. }
  10. type Resource struct {
  11. list map[string]OneResource
  12. }
  13. func New() *Resource {
  14. r := Resource{}
  15. r.list = map[string]OneResource{}
  16. return &r
  17. }
  18. func (this *Resource) Add(path string, ctype string, bytes []byte) {
  19. // Do not add if already in resources list
  20. if _, ok := this.list[path]; ok == true {
  21. return
  22. }
  23. // Add to resources list
  24. this.list[path] = OneResource{
  25. Path: path,
  26. Ctype: ctype,
  27. Bytes: bytes,
  28. }
  29. }
  30. func (this *Resource) Response(w http.ResponseWriter, r *http.Request, before func(w http.ResponseWriter, r *http.Request, i *OneResource), after func(w http.ResponseWriter, r *http.Request, i *OneResource)) bool {
  31. // Do not process if this is not necessary
  32. if len(r.URL.Path) <= 1 {
  33. return false
  34. }
  35. // Check for resource
  36. res, ok := this.list[r.URL.Path[1:]]
  37. if ok == false {
  38. return false
  39. }
  40. // Call `before` callback
  41. if before != nil {
  42. before(w, r, &res)
  43. }
  44. // Send resource
  45. w.Header().Set("Content-Type", res.Ctype)
  46. w.Write(res.Bytes)
  47. // Call `after` callback
  48. if after != nil {
  49. after(w, r, &res)
  50. }
  51. return true
  52. }